具体demo如下:
const express = require('express');
const bodyParser = require("body-parser")
const app = express();
const articles = [{title:'这是一篇文章'}]
const port = process.env.PORT || 3000;
app.use(bodyParser.json()); //支持编码为JSON的请求消息体
app.use(bodyParser.urlencoded({extended:true})) //支持编码为表单的请求消息体
app.get('/',(req,res)=>{
res.send('Hello World!!!')
})
app.get('/articles',(req,res,next)=>{
res.send(articles)
})
app.post('/articles',(req,res,next)=>{
const article = {title:req.body.title};
articles.push(article);
res.send(article)
})
app.get('/articles/:id',(req,res,next)=>{
const id = req.params.id;
console.log("Fetching:",id);
res.send(articles[id]);
})
app.delete('/articles/:id',(req,res,next)=>{
const id = req.params.id;
console.log("Deleting:",id)
delete articles[id];
resw.send({message:"Deleted"})
})
app.listen(port,()=>{
console.log('Express web app available at localhost:'+port)
})
module.exports = app;
用postman调接口,成功!
注意: post逻辑实现要依赖body-parser插件解析请求体