Node.js发送带Body参数POST请求时服务端req.body值为undefined问题
问题根因
当前服务端仅配置了bodyParser.json()中间件,仅支持解析请求头Content-Type为application/json格式的请求体。原有客户端发送的是application/x-www-form-urlencoded格式的参数,服务端无法正常解析,因此req.body下的字段全部为undefined。
你在Postman中可以请求成功,是因为Postman默认发送的是JSON格式的请求参数,匹配服务端的解析规则。
仅修改客户端的解决方案
直接调整客户端请求的参数格式和请求头,改为发送JSON格式的请求体即可,修改后的getTestToken函数代码如下:
function getTestToken() { const parameters = { "grant_type": "client_credentials", "client_id": "admin", "client_secret": "admin" }; // 直接将参数序列化为JSON字符串,不再使用querystring格式化 const post_data = JSON.stringify(parameters); const options = { headers: { // 修改Content-Type为JSON格式 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(post_data) }, method: "POST" } const token_endpoint = "http://localhost:8081/token"; const token_request = http.request(token_endpoint, options); token_request.once("error", err => {throw err}); token_request.once("response", (token_stream) => getFromStream(token_stream)); token_request.write(post_data); token_request.end(); }
修改后运行客户端即可得到预期的输出结果。
内容的提问来源于stack exchange,提问作者parsecer
相关产品推荐
相关产品推荐

