微信小程序自学 随笔3 Failed to load resou

2017-02-02  本文已影响3892人  jlnbda3488375

关于wx.request产生 “Failed to load resource: the server responded with a status of 400 (Bad Request)” 的解决办法

    //xxxx.js
    var request_URL='https://xxx';
    Page({
        data:{},
        onLoad:function(){
          wx.request({
            url:request_URL,
            data:{},
            header:{
              'content-type': 'application/json'
            },
            success: function(res) {
              console.log(res.data)
            }
          })
        }
    })

解决办法:将ContentType改为 "application/x-www-form-urlencoded" ;

http://blog.csdn.net/mhmyqn/article/details/25561535
最近在看书时才真正搞明白,服务器为什么会对表单提交和文件上传做特殊处理,因为表单提交数据是名值对的方式,且Content-Type为application/x-www-form-urlencoded,而文件上传服务器需要特殊处理,普通的post请求(Content-Type不是application/x-www-form-urlencoded)数据格式不固定,不一定是名值对的方式,所以服务器无法知道具体的处理方式,所以只能通过获取原始数据流的方式来进行解析。

jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded,所以服务器能够正确解析,而使用原生ajax请求时,如果不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。

上一篇 下一篇

猜你喜欢

热点阅读