只用来参考的
app.js
const express = require('express'); const morgan = require('morgan'); const tourRouter = require('./routes/tourRoutes'); const userRouter = require('./routes/userRoutes'); const app=express(); // 1 middleware if(process.env.NODE_ENV==='development'){ app.use(morgan('dev')) } app.use(express.json()); app.use(express.static(`${__dirname}/public`)) // 2 // const tours = JSON.parse(fs.readFileSync(`${__dirname}/dev-data/data/tours-simple.json`)); // app.get('/api/v1/tours',getAllTours); // app.get('/api/v1/tours/:id',getTours) // app.post('/api/v1/tours',createTours) // app.patch('/api/v1/tours/:id',updateTour) // app.delete('/api/v1/tours/:id',deleteTours) //3 ROUTES app.use('/api/v1/tours',tourRouter) app.use('/api/v1/users',userRouter) module.exports=app; // 4 START SERVER
server.js
const dotenv = require('dotenv'); const mongoose = require('mongoose') const app = require('./app'); dotenv.config( { path:'./config.env' }); // console.log(process.env) // console.log(process.env.PORT) const port=3000 || process.env.PORT; app.listen(port,()=>{ console.log(`App runing on port ${port}....`); });
package.json
{ "name": "4-natours", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start:prod": "set NODE_ENV=production && nodemon server.js", "start:dev": "nodemon server.js" }, "author": "", "license": "ISC", "dependencies": { "dotenv": "^16.0.3", "express": "^4.18.2", "mongoose": "^7.2.1", "morgan": "^1.10.0", "prettier": "^2.8.8" } }
跑起来是
node run start
routes.js
tourRoutes.js
const express = require('express'); const tourController=require('./../controller/tourController') const tourRouter =express.Router(); tourRouter.param('id',tourController.checkID) //Create a checkbody middleware //Check if body contains the name and price property //If not, send back 400 () //add it to the post bandler stack tourRouter .route('/') .get(tourController.getAllTours) .post(tourController.checkBody,tourController.createTours) tourRouter.route('/:id') .get(tourController.getTours) .patch(tourController.updateTour) .delete(tourController.deleteTours) module.exports=tourRouter;
userRouter.js
const express = require('express'); const tourController=require('./../controller/tourController') const tourRouter =express.Router(); tourRouter.param('id',tourController.checkID) //Create a checkbody middleware //Check if body contains the name and price property //If not, send back 400 () //add it to the post bandler stack tourRouter .route('/') .get(tourController.getAllTours) .post(tourController.checkBody,tourController.createTours) tourRouter.route('/:id') .get(tourController.getTours) .patch(tourController.updateTour) .delete(tourController.deleteTours) module.exports=tourRouter;
***************MVC**********************
controler
tourController.js
const fs = require('fs'); const tours = JSON.parse(fs.readFileSync(`${__dirname}/../dev-data/data/tours-simple.json`)); exports.checkID = (req,res,next,val)=>{ console.log(`Tour id is : ${val}`) if(req.params.id * 1 > tours.length){ return res.status(404).json({ status:'fail', message:'Invalid ID' }) } next() } exports.checkBody = (req,res,next)=>{ if(!req.body.name || !req.body.price){ return res.status(400).json({ status:'fail', message:'Missing name or price' }) } next() } exports.getAllTours=(req,res)=>{ res.status(200).json({ status:'sucess', data:{ tours:tours } }) } exports.getTours=(req,res)=>{ console.log(req.params) const id=req.params.id *1 const tour= tours.find(el=>el.id===id) res.status(200).json({ status:'sucess', data:{ tour:tour } }) } exports.createTours=(req,res)=>{ const newId = tours[tours.length -1].id+1; const newTour =Object.assign({id:newId},req.body); tours.push(newTour); fs.writeFile(`${__dirname}/dev-data/data/tours-simple.json`,JSON.stringify(tours),err=>{ res.status(201).json({ status:'success', data:{ tours:newTour } }) }) } exports.updateTour=(req,res)=>{ res.status(200).json({ status:'success', data:{ tour:'<Update tour here ...>' } }) } exports.deleteTours=(req,res)=>{ res.status(204).json({ status:'success', data:null }) }
userController.js
const fs = require('fs'); const tours = JSON.parse(fs.readFileSync(`${__dirname}/../dev-data/data/tours-simple.json`)); exports.getAllUser = (req,res)=>{ res.status(500),json({ status:'error', messages:'this route is not yer' }) } exports.getUser=(req,res)=>{ console.log(req.params) const id=req.params.id *1 const tour= tours.find(el=>el.id===id) if(!tour){ return res.status(404).json({ status:'fail', message:'invalid ID' }) } res.status(200).json({ status:'sucess', data:{ tour:tour } }) } exports.createUser=(req,res)=>{ const newId = tours[tours.length -1].id+1; const newTour =Object.assign({id:newId},req.body); tours.push(newTour); fs.writeFile(`${__dirname}/dev-data/data/tours-simple.json`,JSON.stringify(tours),err=>{ res.status(201).json({ status:'success', data:{ tours:newTour } }) }) } exports.updateUser=(req,res)=>{ if(req.params.id * 1 > tours.length){ return res.status(404).json({ status:'fail', message:'invalid ID' }) } res.status(200).json({ status:'success', data:{ tour:'<Update tour here ...>' } }) } exports.deleteUser=(req,res)=>{ if(req.params.id * 1 > tours.length){ return res.status(404).json({ status:'fail', message:'Invalid ID' }) } res.status(204).json({ status:'success', data:null }) }
data
M
/* eslint-disable */ const tour5 = { id: 5, name: 'The Sports Lover', startLocation: 'California, USA', nextStartDate: 'July 2021', duration: 14, maxGroupSize: 8, difficulty: 'difficult', avgRating: 4.7, numReviews: 23, regPrice: 2997, shortDescription: 'Surfing, skating, parajumping, rock climbing and more, all in one tour', longDescription: 'Nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nVoluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur!' };
标签:node,status,req,const,res,express,mvc,tours,id From: https://www.cnblogs.com/hechunfeng/p/17476346.html