如何使用express router提取json?

如何使用express router提取json?,express,xmlhttprequest,Express,Xmlhttprequest,我正在使用post将JSON对象发送到我的服务器: const xhr = new XMLHttpRequest(); var params = { firstname: "Joe", lastname: "Bloggs" }; xhr.open('post', '/api/endpoint'); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.respo

我正在使用post将JSON对象发送到我的服务器:

 const xhr = new XMLHttpRequest();
 var params = {
     firstname: "Joe",
     lastname: "Bloggs"
 };
 xhr.open('post', '/api/endpoint');
 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
 xhr.responseType = 'json';
 xhr.addEventListener('load', () => {
     ...
 });
 xhr.send(JSON.stringify(params));
我正在使用express处理请求:

...
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
...
然后,在我的api端点,我正在使用Express Router:

const express = require('express');
const router = new express.Router();
router.post('/endpoint', (req, res) => {
    console.log(req.body);
});
当我打印出req.body时,我得到以下信息:

{ '{"firstname":"Joe","lastname":"Bloggs"}': '' }
如果使用JSON.parse(req.body),则会出现以下错误:

TypeError:无法将对象转换为基元值 在JSON.parse()处


如何以我可以使用的格式获取有效负载的内容,即json对象?

您表示将在此处发送
应用程序/x-www-form-urlencoded

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
在这里您可以发送JSON:

xhr.send(JSON.stringify(params));
这显然违反了法律。在发出请求时,请确保遵守向服务器指示的格式:

var payload = 'firstname=' + encodeURIComponent(params.firstname) + 
              '&lastname=' + encodeURIComponent(params.lastname);
xhr.send(payload);
另一方面,如果您希望发送JSON内容,则可以在服务器上添加相应的主体解析器:

app.use(bodyParser.json({ type: 'application/json' }))
然后在客户端上设置适当的内容类型请求标头:

xhr.setRequestHeader('Content-type', 'application/json');
现在您可以在发送请求时
JSON.stringify

xhr.send(JSON.stringify(params));

在api端点,可以从
req.body
(无需使用
JSON.parse
)提取JSON

在发送的请求头中使用“application/JSON”的内容类型,而不是“application/x-www-form-urlencoded”。如果还将bodyparser.json用作中间件,则req.body将是有效的json。您不必通过JSON.parse对其进行转换。您可以只使用一种类型的bodyparser,或者express能够根据内容类型检测到它吗?我在项目中使用多个bodyparser。我不确定,但我认为中间件会根据标题中定义的内容类型过滤内容。