Javascript Axios Http 客户端 - 如何使用表单参数构造 Http Post url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31756756/
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
Axios Http client - How to construct Http Post url with form params
提问by mmraj
I am trying to create a postHTTP request with some form parameters that are to be set. I am using the axios with node server. I already have a java code implementation of constructing a url as given below:
我正在尝试使用要设置的一些表单参数创建 postHTTP 请求。我正在将 axios 与节点服务器一起使用。我已经有一个构建 url 的 java 代码实现,如下所示:
JAVA CODE:
爪哇代码:
HttpPost post = new HttpPost(UriBuilder.fromUri (getProperty("authServerUrl"))
.path(TOKEN_ACCESS_PATH).build(getProperty("realm")));
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new NameValuePair("username",getProperty ("username")));
formParams.add(new NameValuePair("password",getProperty ("password")));
formParams.add(new NameValuePair("client_id, "user-client"));
I am trying to do the same thing in axios.
我正在尝试在 axios 中做同样的事情。
AXIOS IMPLEMENTATION:
AXIOS 实现:
axios.post(authServerUrl +token_access_path,
{
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}).then(function(response) {
console.log(response); //no output rendered
}
Is the approach to set these form params on the post request correct?
在发布请求上设置这些表单参数的方法是否正确?
回答by cperez
You have to do the following:
您必须执行以下操作:
var querystring = require('querystring');
//...
axios.post(authServerUrl + token_access_path,
querystring.stringify({
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
console.log(response);
});
回答by jhickok
Why pull in another library or module to do something so simple with pure vanilla JavaScript? It's really one line of JS to produce the desired data to submit in your POST request.
为什么要引入另一个库或模块来使用纯原生 JavaScript 做一些如此简单的事情?它实际上是一行 JS 来生成要在 POST 请求中提交的所需数据。
// es6 example
const params = {
format: 'json',
option: 'value'
};
const data = Object.entries(params)
.map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
.join('&');
console.log(data);
// => format=json&option=value
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data,
url: 'https://whatever.com/api',
};
const response = await axios(options); // wrap in async function
console.log(response);