我有一些参数,我想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
  }); 

如何在请求中包含表单编码的参数?


当前回答

只使用

import  qs from "qs";
 let data = {
        'profileId': this.props.screenProps[0],
        'accountId': this.props.screenProps[1],
        'accessToken': this.props.screenProps[2],
        'itemId': this.itemId
    };
    return axios.post(METHOD_WALL_GET, qs.stringify(data))

其他回答

在最初的示例中,您有一个transformRequest函数,它将对象转换为Form Encoded数据。

在修改后的示例中,您已将其替换为JSON。stringify将对象转换为JSON。

在这两种情况下,你都有'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',所以在这两种情况下,您都声称要发送表单编码的数据。

使用你的表单编码函数,而不是JSON.stringify。


重新更新:

在第一个获取示例中,将主体设置为JSON值。

现在您已经创建了一个Form Encoded版本,但是您没有将主体设置为该值,而是创建了一个新对象,并将Form Encoded数据设置为该对象的属性。

不要创建额外的对象。把你的值赋给身体。

你必须自己把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。

如果你正在使用JQuery,这也是有效的。

fetch(url, {
      method: 'POST', 
      body: $.param(data),
      headers:{
        'Content-Type': 'application/x-www-form-urlencoded'
      }
})

对于上传表单编码的POST请求,我建议使用FormData对象。

示例代码:

var params = {
    userName: 'test@gmail.com',
    password: 'Password!',
    grant_type: 'password'
};

var formData = new FormData();

for (var k in params) {
    formData.append(k, params[k]);
}

var request = {
    method: 'POST',
    headers: headers,
    body: formData
};

fetch(url, request);

您可以使用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);
    }
});