我有一些参数,我想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
});
如何在请求中包含表单编码的参数?
你可以使用FormData和URLSearchParams发布为application/x-www-form-urlencoded,示例如下:
如果你有一个表格:
<form>
<input name="username" type="text" />
<input name="password" type="password" />
<button type="submit">login</button>
</form>
您可以添加使用下面的JS来提交表单。
const form = document.querySelector("form");
form.addEventListener("submit", async () => {
const formData = new FormData(form);
try {
await fetch("https://example.com/login", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams(formData),
});
} catch (err) {
console.log(err);
}
});
根据规范,使用encodeURIComponent不会给你一个符合要求的查询字符串。州:
Control names and values are escaped. Space characters are replaced by +, and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by %HH, a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A).
The control names/values are listed in the order they appear in the document. The name is separated from the value by = and name/value pairs are separated from each other by &.
问题是,encodeURIComponent将空格编码为%20,而不是+。
表单主体应该使用其他答案中显示的encodeURIComponent方法的变体进行编码。
const formUrlEncode = str => {
return str.replace(/[^\d\w]/g, char => {
return char === " "
? "+"
: encodeURIComponent(char);
})
}
const data = {foo: "bar߃©˙∑ baz", boom: "pow"};
const dataPairs = Object.keys(data).map( key => {
const val = data[key];
return (formUrlEncode(key) + "=" + formUrlEncode(val));
}).join("&");
// dataPairs is "foo=bar%C3%9F%C6%92%C2%A9%CB%99%E2%88%91++baz&boom=pow"
你必须自己把x-www-form-urlencoded有效负载放在一起,就像这样:
var details = {
'userName': 'test@gmail.com',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('https://example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
})
注意,如果你在一个(足够现代的)浏览器中使用fetch,而不是React Native,你可以创建一个URLSearchParams对象并使用它作为主体,因为fetch标准声明,如果主体是一个URLSearchParams对象,那么它应该被序列化为application/x-www-form-urlencoded。然而,你不能在React Native中这样做,因为React Native没有实现URLSearchParams。
*/ import this statement */
import qs from 'querystring'
fetch("*your url*", {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
body: qs.stringify({
username: "akshita",
password: "123456",
})
}).then((response) => response.json())
.then((responseData) => {
alert(JSON.stringify(responseData))
})
在使用npm i querystring后,保存它的工作很好。
在最初的示例中,您有一个transformRequest函数,它将对象转换为Form Encoded数据。
在修改后的示例中,您已将其替换为JSON。stringify将对象转换为JSON。
在这两种情况下,你都有'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',所以在这两种情况下,您都声称要发送表单编码的数据。
使用你的表单编码函数,而不是JSON.stringify。
重新更新:
在第一个获取示例中,将主体设置为JSON值。
现在您已经创建了一个Form Encoded版本,但是您没有将主体设置为该值,而是创建了一个新对象,并将Form Encoded数据设置为该对象的属性。
不要创建额外的对象。把你的值赋给身体。