// 第一版,node的httpp // const http = require('http'); // const server=http.createServer((req,res)=>{ // if(req.url==='/'){ // res.write('hello world') // res.end(); // } // if(req.url==='/api/courses'){ // res.write(JSON.stringify([1,2,3])) // res.end(); // } // }) // server.listen(3000) // console.log('Listening on port 3000...') // 第二版,node http库 express const exp = require('constants'); const express=require('express') const app =express(); app.use(express.json()) const courses=[ {id:1,name:'course1'}, {id:2,name:'course2'}, {id:3,name:'course3'} ] app.get('/',(req,res)=>{ res.send('hello world') }) app.get('/api/courses',(req,res)=>{ res.send(courses) }) //Joi 库可以做验证 app.post('/api/courses',(req,res)=>{ if(!req.body.name || req.body.name.length<3){ //400 Bad Request res.status(400).send('Name is required and ....') } const course={ id:courses.length+1, name:req.body.name } courses.push(course) res.send(course) }) app.get('/api/courses/:id',(req,res)=>{ let course=courses.find(c=>c.id===parseInt(req.params.id)) if(!course)//404 res.status(404).send('the course with the give ID not found') res.send(course) }) // app.get('/api/posts/:year/:month',(req,res)=>{ // res.send(req.query)req.params, // }) const port=process.env.PORT||3000 app.listen(port,()=>{ console.log(`Listening on port ${port}...`) }) // app.post() // app.put() // app.delete()
标签:node,const,restAPI,app,req,courses,例子,res,id From: https://www.cnblogs.com/hechunfeng/p/17530633.html