node.js 节点 js 发送带有原始请求正文的 post 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33637105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node js send post request with raw request body
提问by Zack Sac S
var req ={
"request": {
"header": {
"username": "name",
"password": "password"
},
"body": {
"shape":"round"
}
}
};
request.post(
{url:'posturl',
body: JSON.stringify(req),
headers: { "content-type": "application/x-www-form-urlencoded"}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
I want to send raw request body in req variable . It is working on postman but in node js i am not able to send the raw json as request body for post request .
我想在 req 变量中发送原始请求正文。它正在处理邮递员,但在节点 js 中,我无法将原始 json 作为 post request 的请求正文发送。
回答by Thomas Bormans
You are trying to send JSON (your reqvariable) but you are parsing it as a String (JSON.stringify(req)). Since your route is expecting JSON, it will probably fail and return an error. Try the request below:
您正在尝试发送 JSON(您的req变量),但您将其解析为 String ( JSON.stringify(req))。由于您的路由需要 JSON,因此它可能会失败并返回错误。试试下面的请求:
request.post({
url: 'posturl',
body: req,
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
});
Instead of setting your headers, you can just add the option json: trueif you are sending JSON.
json: true如果要发送 JSON ,则无需设置标头,只需添加选项即可。
回答by Kelly Keller-Heikkila
Change the Content-Typeto application/json, since your body is in JSON format.
将 更改Content-Type为application/json,因为您的正文采用 JSON 格式。
回答by Ram
Adding the 'Content-Length' in the header for the string that is added in the body , will resolve this issue. It worked for me.
在正文中添加的字符串的标题中添加“内容长度”将解决此问题。它对我有用。
headers:{"Cache-Control": "no-cache", "Content-Type":"application/json;charset=UTF-8",'Content-Length': req.length}
headers:{"Cache-Control": "no-cache", "Content-Type":"application/json;charset=UTF-8", 'Content-Length': req.length}

