Express 获取 POST请求参数为undefined?【已解决】

在 express 中获取 post 请求参数时会返回 {} 或者 undefined

问题原因: Express默认只支持jsonx-www-form-urlencoded格式的数据.

解决办法:
在请求中需要设置Content-typeapplication/x-www-form-urlencoded

init();
function init() {
  var xhr = new XMLHttpRequest();
  xhr.addEventListener('readystatechange', readystatechangeHandler);
  xhr.open('post', 'http://localhost:3000/users/login');
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send('a=10&b=20');
}

function readystatechangeHandler() {
  if (this.status === 200 && this.readyState === 4) console.log(JSON.parse(this.response));
}

然后在服务端需要下载一个解析的中间件 body-parser

// 引入
var app = require('express');
var bodyParser = require('body-parser');
// 使用中间件
app.use(bodyParse.json()) // 支持 json 格式
// 使用第三方插件 qs 来处理
app.use(bodyParse.urlencoded({extended : true}))

// post 请求
app.post("/users/login", function(req, res) {
  console.log(req.body);  // 这样就可以获取 post 的参数了
});

在这里插入图片描述

发布了19 篇原创文章 · 获赞 13 · 访问量 5095

猜你喜欢

转载自blog.csdn.net/actionActivity/article/details/104557518