2016-12-15 1 views
0

node.js + Express 애플리케이션이 있습니다. 그것은 제 3 자 서비스에 제공 한 webhook을 가지고 있습니다.Node.js가 내 webhook에서 POST JSON 데이터를 읽을 수 없습니다.

{ "split_info" "널 (null)", "CUSTOMERNAME": "판매자 이름", "additionalCharges": "널 (null)"이 서비스는 다음과 같이 보입니다 JSON 본체 내은 webhook에 POST 요청을 보냅니다 "paymentMode": "CC", "해시": "a31ff1b91fd9b8ae9c82f38b02348d21fsdfd86cc828ac9a0acf82050996372cc656de3db0fe3bf9af52b73a182a77787241f3e19ec893391607301b03e70db8" "상태": "지불 릴리스", "paymentId": "551731", "인 ProductInfo": "인 ProductInfo", "customerEmail" " "value": "100.0", "udf2": "null", "notificationId": "4", "customer_highlight": " udf1 ":"null ", "udf5 ":"널 (null) ","udf4 ":"널 (null) ","udf3 ":"널 (null) ","ERROR_MESSAGE ":"아니 오류 "} 내가 POST 데이터를 읽기 위해 몸 파서 모듈을 사용하고

. 그러나 req.body 할 때 [object Object] 제공, JSON.stringify (req.body) 할 경우 {} 빈 즉 제공합니다. req.body.paymentMode와 같은 응답의 키에 액세스하려고 시도하면 정의되지 않은 상태가됩니다. mywebhook.js

var express = require('express'); 
var router = express.Router(); 

router.post('/success', function(req, res){ 

    //this is where I need to strip the JSON request 
    //req.body or JSON.stringify(req.body) or anything that works 
    //if everything is okay then I send 
    res.sendStatus(200); 

}); 

module.exports = router; 

app.js은 다음과 같습니다 : 여기

은은 webhook 내 라우터 코드입니다

var express = require('express');        
var exphbs = require('express-handlebars'); 
var router = express.Router();         
var bodyParser = require('body-parser'); 

var mywebhook = require('./routes/mywebhook'); 

var app = express(); 

. 
. 
. 
app.use(bodyParser.urlencoded({'extended':'true'}));   // parse application/x-www-form-urlencoded 
app.use(bodyParser.json());          // parse application/json 
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json 


app.use('/callwebhook', mywebhook); 

. 
. 
. 
so on   

내가 뭔가를 누락되거나하고있는 중이 야 확신 잘못된 것이지만 그것을 파악할 수는 없습니다.

감사합니다.

+1

요청의'Content-type'은'application/vnd.api + json'입니까? 이것은 나에게 이상한 것처럼 보인다. – svens

+0

맞습니다. hookbin.com을 사용하여 thrid party webhook을 테스트했을 때 콘텐츠 유형이 다음과 같다고 말합니다 : */*. 그래서 내 app.js의 콘텐츠 유형을 app.use (bodyParser.json ({type : '*/*'})))로 변경해야합니다. – codeinprogress

+0

좋아, 유형을 '*/*'로 변경했지만 req.body는 여전히 비어 있습니다. – codeinprogress

답변

0

나는 마침내 무슨 일이 일어나고 있는지 발견했습니다.

body-parser가 작동하는 방식은 Content-Type을 이해하는 요청 만 구문 분석하려고한다는 것입니다. 이것은 주로 스택을 만들 수 있기 때문에 (충돌없이 여러 파서 유형을 app.app로 사용) 일반적으로 실패 할 요청을 구문 분석하지 않으므로 (Content-Type : text/html은 예를 들어 JSON.parse).

*/*; charset=UTF-8이 유효한 Content-Type 헤더 값 기간이 아니 어서 보냈습니다. body-parser 모듈은 횡설수설하기 때문에 그것을 받아들이기를 거부했습니다. 이 모듈을 사용하면 필터링을 수행하려는 모든 사용자 정의 논리를 넣을 수있는 기능을 설정할 수 있습니다.

이 웹 훅 케이스의 라우터 코드에 본문 파서를 넣어야했습니다.

var bodyParser = require('body-parser'); 
var customParser = bodyParser.json({type: function(req) { 
    return req.headers['content-type'] === '*/*; charset=UTF-8'; 
}}); 

router.post('/success', customParser, function(req, res){ 
    console.log(JSON.stringify(req.body)); 
}); 

@svens 귀하의 도움에 감사드립니다.

관련 문제