HTTP请求中的form data和request payload的区别

区别就是:

当POST请求的请求头里设置Content-Type: application/x-www-form-urlencoded(默认), 参数在请求体以标准的Form Data的形式提交,以&符号拼接,参数格式为key=value&key=value&key=value

当使用AJAX原生POST请求,请求头里设置Content-Type:application/json,请求的参数会显示在Request Payload中,参数格式为JSON格式:{“key”:”value”,”key”:”value”…},这种方式可读性会更好。

当参数是JSON对象时,默认的Content-Type是application/json。

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

此时传递的参数是Request Payload格式{firstName:“Fred”,lastName:“Flintstone”}

如果出现No ‘Access-Control-Allow-Origin’ header is present on the requested resource
的错误,则是跨域问题。本人喜欢直接配置服务器来解决跨域:例如Nginx配置:Nginx配置跨域请求

当参数是JSON字符串时,默认的Content-Type是application/x-www-form-urlencoded。

axios.post('/user', JSON.stringify({
    firstName: 'Fred',
    lastName: 'Flintstone'
  }))
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

此时传递的参数是Form Data格式key : value

{"firstName":"Fred","lastName":"Flintstone"}:

如上。其实这是一个无效的数据,key为{“firstName”:“Fred”,“lastName”:“Flintstone”},value为空。

要想使用application/x-www-form-urlencoded格式,需要进行数据转换,虽然有两种方式URLSearchParams和qs两种方式。我更喜欢使用qs库的方式,代码如下:

axios.interceptors.request.use((req) => {
    if (req.method === 'post') {
     req.data = qs.stringify(req.data);
    }
    return req;
}, (error) => Promise.reject(error));

之后使用axios的时候,只需要传递json对象就可以:

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

原文:https://blog.csdn.net/qq_27008807/article/details/78945990

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值