Post request for WeChat development pitfalls

零下一度
Release: 2017-05-20 16:09:57
Original
2969 people have browsed it

1.post request

wx.request(OBJECT)
wx.request
initiates an HTTPS request. A WeChat applet can only have 5 network request connections at the same time.
Official website description

Parameter nameTypeRequired Description
urlString is developed by Or server interface address
dataObject, StringNoRequested parameters
headerObjectNoSet the request header, Referer cannot be set in the header
methodStringNoDefault is GET, valid values: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
successFunctionNoReceive the callback function returned successfully by the developer service, res = {data: 'Return from the developer server Content'}
failFunctionNoCallback function for interface call failure
completeFunctionNoThe callback function at the end of the interface call (will be executed if the call is successful or failed)

WeChat applet example

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
        x: '' , 
        y: ''
   }, 
  header: { 
    'content-type': 'application/json' 
  }, 
  success: function(res) { 
    console.log(res.data) 
  }
})
Copy after login

This request GET method is OK, and the header does not need to be added.
But POST has a big problem.

I use the following code for debugging (Code 1):

wx.request({
    url: ApiHost + '/?service=default.getOrderInfo',
    data: {
      'order_id': order_id
    },
    method: 'POST',
    success: function (res) {
      // console.log(res);
      if (res.data.ret == 200) {
       //something to do
      }
      else{
       //something to do
      }
    }
    fail: function (res) {
      console.log(res);
    }
  });
Copy after login

Pay attention to the picture below, the prompts in the WeChat development tool:

Post request for WeChat development pitfalls

2016-12-21_111056.png

POST request will put the value of data in the Request Payload instead of the Query String Parameters. If the backend server If you don't pay attention, you won't be able to get the data.
There are many reform laws on the Internet, which are like this. ----Add the header

wx.request({
    url: ApiHost + '/?service=default.getOrderInfo',
    data: {
      //数据urlencode方式编码,变量间用&连接,再post
      'order_id='+order_id
    },
    method: 'POST',
    header:{
      'content-type':'application/x-www-form-urlencoded'
    },
    success: function (res) {
      // console.log(res);
      if (res.data.ret == 200) {
       //something to do
      }
      else{
       //something to do
      }
    }
    fail: function (res) {
      console.log(res);
    }
  });
Copy after login

If you modify it like this, the backend does not need special processing.
But...

Because I still want to use the standard method, the only way is to modify the backend server.
I am using the Phalapi framework here, I recommend it~~~

if(DI()->request->getHeader('content-type'))
{    
  $contentType = DI()->request->getHeader('content-type');
}
if(!empty($contentType)&&(strtolower(@$contentType) === 'application/json'))
{
    $HTTP_RAW_POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : "{}";
    DI()->request = new PhalApi_Request(array_merge($_GET,json_decode($HTTP_RAW_POST_DATA, true)));
}
Copy after login

Finally, I passed the debugging using code one on the PC. Use standard requests and do not use the application/x-www-form-urlencoded mode.

But...when I use real machine debugging, why can't I receive the request parameters? Strange things. . . . . . . . .
Finally through packet capture analysis

Real machine end

POST /?service=default.getOrderInfo HTTP/1.0
Host: proxy
Connection: close
Content-Length: 43
Content-Type: application/json
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36 
MicroMessenger/6.5.1 NetType/WIFI Language/zh_CN
Referer: https://servicewechat.com/###/0/page-frame.html
Accept-Language: zh-cn

{"order_id":"011T00wO0gZVR72P89tO0DFNvO0T00w0"}
Copy after login

PC simulation development end

POST /?service=default.getOrderInfo HTTP/1.0
Host: proxy
Connection: close
Content-Length: 43
Origin: http://###.appservice.open.weixin.qq.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 
appservice webview/100000
content-type: application/json
Accept: */*
Referer: https://servicewechat.com/####/devtools/page-frame.html
Accept-Encoding: gzip, deflate, br

{"order_id":"011T00wO0gZVR72P89tO0DFNvO0T00w0"}
Copy after login

Finally find the difference :
Content-Type and content-type
The default of the simulator is content-type
The default of the real machine is Content-Type
The back-end server adds processing of Content-Type and it is done.

【Related recommendations】

1. WeChat public account platform source code download

2. 小 Pigcms (PigCms) micro-e-commerce System operation version (independent Weidian mall + three-level distribution system)

3. WeChat People Network v3.4.5 Advanced Commercial Edition WeChat Rubik’s Cube Source Code

The above is the detailed content of Post request for WeChat development pitfalls. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!