踩過的一個坑,獲取不到express post請求參數,如下
const express = require("express");
const app = express();
// localhost:8090/hello
app.get("/hello",function(req,res){
res.send("hello huangbaokang");
})
/**
POST localhost:8090/world
Content-type: application/x-www-form-urlencoded
POST_BODY:
variable1=avalue&variable2=1234&variable3=anothervalue
*/
app.post("/world",function(req,res){
console.log(req.body);
res.send(req.body);
})
app.listen(8090,function(){
console.log("服務器已啓動")
})
使用Http Requester測試,首先需要安裝這個插件,運行使用快捷鍵ctrl+alt+R
,以下是github地址。
https://github.com/braindamageinc/SublimeHttpRequester
測試post的時候,發現控制檯輸出undefined。
解決辦法
POST請求和GET請求不太一樣,req.query獲取不到傳過來的參數,因此需要在index.js中使用json解析中間件(body-parser)
npm install body-parser
// 引入json解析中間件
var bodyParser = require('body-parser');
// 添加json解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
// localhost:8090/hello
app.get("/hello",function(req,res){
res.send("hello huangbaokang");
})
/**
POST localhost:8090/world
Content-type: application/x-www-form-urlencoded
POST_BODY:
variable1=avalue&variable2=1234&variable3=anothervalue
*/
app.post("/world",function(req,res){
console.log(req.body);
res.send(req.body);
})
app.listen(8090,function(){
console.log("服務器已啓動")
})