我有一些参数,我想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
});
如何在请求中包含表单编码的参数?
更简单:
fetch('https://example.com/login', {
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'userName': 'test@gmail.com',
'password': 'Password!',
'grant_type': 'password'
})
});
文档:https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
*/ 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后,保存它的工作很好。
更简单:
fetch('https://example.com/login', {
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'userName': 'test@gmail.com',
'password': 'Password!',
'grant_type': 'password'
})
});
文档:https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
您可以使用react-native-easy-app,更容易发送http请求和制定拦截请求。
import { XHttp } from 'react-native-easy-app';
* Synchronous request
const params = {name:'rufeng',age:20}
const response = await XHttp().url(url).param(params).formEncoded().execute('GET');
const {success, json, message, status} = response;
* Asynchronous requests
XHttp().url(url).param(params).formEncoded().get((success, json, message, status)=>{
if (success){
this.setState({content: JSON.stringify(json)});
} else {
showToast(msg);
}
});