express 发送post请求

踩过的一个坑,获取不到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("服务器已启动")
})


在这里插入图片描述

发布了1237 篇原创文章 · 获赞 317 · 访问量 227万+

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/105677867