Node.js는 PHP 컬 포스트 데이터 req.body가 비어 있는 처리를 얻습니다.

巴扎黑
풀어 주다: 2016-11-10 10:30:22
원래의
2191명이 탐색했습니다.

노드는 express4와 body-parser를 사용하여 php 컬 데이터를 구문 분석하지만, 얻은 req.body는 {}이고 헤더가 설정되어 있습니다.

전제 지식:

body-parser는 다중/양식 데이터 구문 분석 기능을 지원하지 않습니다. 바이너리 데이터를 전달하거나 파일을 업로드하는 경우에는 사용할 수 없습니다.

Node.js 본문 구문 분석 미들웨어.

복잡하고 일반적으로 큰 특성으로 인해 다중 부분 본문을 처리하지 않습니다. 다중 부분 본문의 경우 다음 모듈에 관심이 있을 수 있습니다.

busboy 및 connect-busboy
multiparty 및 connect-multiparty
강력한
multer
이 모듈은 다음 파서를 제공합니다.

JSON 본문 파서
Raw body 파서
텍스트 본문 파서
URL 인코딩 양식 본문 파서

참조:
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}";  
    }
로그인 후 복사

노드 코드

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[&#39;content-type&#39;]  
  return typeis(value, types)  
}
로그인 후 복사



여기에서 확인 req.headers['content-type']은 multipart/form-data이고 유형은 application/x-www-form-urlencoded입니다.

PHP가 컬을 실행할 때 postData는 배열이고, 데이터 인코딩을 multipart/form-data

Java 코드

참고:

배열을 CURLOPT_POSTFIELDS에 전달하면 cURL이 데이터는 multipart/form-data로 인코딩되지만 URL 인코딩 문자열을 전달하면 데이터는 application/x-www-form-urlencoded로 인코딩됩니다.



PHP 코드 수정

Java 코드

curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode(json_encode($postData)));
로그인 후 복사


관련 라벨:
php
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!