我有一些参数想要以表单编码的方式POST到我的服务器:
{
'userName': 'test@gmail.com',
'password': 'Password!',
'grant_type': 'password'
}
我像这样发送我的请求(目前没有参数)
var obj = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
};
fetch('https://example.com/login', obj)
.then(function(res) {
// Do stuff with result
});
我该如何在请求中包含表单编码的参数?
const formBody = Object.keys(details).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(details[key])).join('&');
该行代码用于将JavaScript对象details
转换为URL编码的字符串格式。具体实现是使用ES6中的箭头函数和模板字符串,以及Object.keys()
方法和Array.prototype.map()
方法对对象属性进行遍历和操作,最终通过Array.prototype.join()
方法将结果拼接成一个字符串。 - Eric Burelconst formBody = Object.entries(details).map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value)).join('&')
。 - Flynn Hou