如何在 node.js 中发布内容类型 ='application/x-www-form-urlencoded' 的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35473265/
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
how to post data in node.js with content type ='application/x-www-form-urlencoded'
提问by rahul
I'm having a problem in posting data in node.js with Content-type: 'application/x-www-form-urlencoded'
我在 node.js 中发布数据时遇到问题 Content-type: 'application/x-www-form-urlencoded'
var loginArgs = {
data: 'username="xyzzzzz"&"password="abc12345#"',
//data: {
// 'username': "xyzzzzz",
// 'password': "abc12345#",
//},
headers: {
'User-Agent': 'MYAPI',
'Accept': 'application/json',
'Content-Type':'application/x-www-form-urlencoded'
}
};
And post request is:
和发布请求是:
client.post("http:/url/rest/login", loginArgs, function(data, response){
console.log(loginArgs);
if (response.statusCode == 200) {
console.log('succesfully logged in, session:', data.msg);
}
It always returns username/passwordincorrect.
它总是返回不正确的用户名/密码。
In the rest api it is said that the request body should be:
在其余 api 中,据说请求正文应该是:
username='provide user name in url encoded
format'&password= "provide password in url encoded format'
回答by Eduardo Cuomo
requestsupports application/x-www-form-urlencodedand multipart/form-dataform uploads. For multipart/relatedrefer to the multipart API.
request支持application/x-www-form-urlencoded和multipart/form-data表单上传。对于multipart/related参考多API。
application/x-www-form-urlencoded (URL-Encoded Forms)
application/x-www-form-urlencoded(URL 编码的表单)
URL-encoded forms are simple:
URL 编码的表单很简单:
const request = require('request');
request.post('http:/url/rest/login', {
form: {
username: 'xyzzzzz',
password: 'abc12345#'
}
})
// or
request.post('http:/url/rest/login').form({
username: 'xyzzzzz',
password: 'abc12345#'
})
// or
request.post({
url: 'http:/url/rest/login',
form: {
username: 'xyzzzzz',
password: 'abc12345#'
}
}, function (err, httpResponse, body) { /* ... */ })
See: https://github.com/request/request#forms
请参阅:https: //github.com/request/request#forms
Or, using request-promise
或者,使用 request-promise
const rp = require('request-promise');
rp.post('http:/url/rest/login', {
form: {
username: 'xyzzzzz',
password: 'abc12345#'
}
}).then(...);
See: https://github.com/request/request-promise#api-in-detail

