node.js擷取php curl post資料req.body為空白的處理

來源:互聯網
上載者:User
node使用了express4和body-parser來解析php curl的資料,但是擷取的req.body是{},設定了header

前提知識:

body-parser不支援解析multi/form-data的功能,如果是傳遞位元據或者檔案上傳,就不能用它了。

Node.js body parsing middleware.

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

busboy and connect-busboy
multiparty and connect-multiparty
formidable
multer
This module provides the following parsers:

JSON body parser
Raw body parser
Text body parser
URL-encoded form body parser

參考:
https://github.com/expressjs/body-parser#bodyparserurlencodedoptions

PHP 代碼

Java代碼

function addCurl($url, $type="get", $postData=null)      {          $ch = curl_init();          $headers[] = 'Connection: Keep-Alive';          $headres[] = 'Content-Type: application/x-www-form-urlencoded;charset=utf-8';                 $headers[] = 'Content-Length: ' . strlen(json_encode($postData));          //$headres[] = 'Content-Type: application/json';          //$headres[] = 'Content-Type: text/html';          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);          curl_setopt($ch, CURLOPT_HEADER, 0);          curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);          if ($type=="get") {              curl_setopt($ch, CURLOPT_POST, 0);          } else {              curl_setopt($ch, CURLOPT_POST, 1);              curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode(json_encode($postData)));          }          curl_setopt($ch, CURLOPT_URL, $url);          $data = curl_exec($ch);          $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);                    if (curl_errno($ch)) {              echo 'Curl error: ' . curl_error($ch) . PHP_EOL;              curl_close($ch);              return false;          }           curl_close($ch);          return ($code == 200) ? $data : "server error,code: . {$code}";      }

node 代碼

Java代碼

var express = require('express')  var bodyParser = require('body-parser')    var app = express()  var urlencodedParser = bodyParser.urlencoded({ extended: false })  app.use(urlencodedParser, function (req, res) {    res.setHeader('Content-Type', 'text/plain')    res.write('you posted:\n')    res.end(JSON.stringify(req.body, null, 2))  })    app.listen(3000, function() {      console.log('Server is running')  })

指定瞭解析方式依然不行。就到body-parser的源碼中一行行調試下去。

找到urlencode.js

Java代碼

// determine if request should be parsed      if (!shouldParse(req)) {        return ('skip parsing'), next()      }



這行shouldParse 返回false
再到type-is.js/index.js 返回false。
var value = req.headers['content-type']


Java代碼

function typeofrequest(req, types_) {    var types = types_    // no body    if (!hasbody(req)) {      return null    }      // support flattened arguments    if (arguments.length > 2) {      types = new Array(arguments.length - 1)      for (var i = 0; i < types.length; i++) {        types[i] = arguments[i + 1]      }    }    // request content type    var value = req.headers['content-type']    return typeis(value, types)  }



發現這裡的req.headers['content-type'] 是 multipart/form-data,而type是application/x-www-form-urlencoded

原來,在php執行curl的時候,postData是數組,會將資料編碼設定為 multipart/form-data

Java代碼

Note:

傳遞一個數組到CURLOPT_POSTFIELDS,cURL會把資料編碼成 multipart/form-data,而然傳遞一個URL-encoded字串時,資料會被編碼成 application/x-www-form-urlencoded。



修改pHP代碼

Java代碼

curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode(json_encode($postData)));
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.