2017-11-23 14 views
0

앱에서 서버로 데이터를 보내고 해당 앱의 게시 방법이 콘텐츠 유형 application/json을 사용하여 이루어졌지만 일반 텍스트입니다. 이 헤더를 지금 변경하려면 앱을 업데이트 할 수 없습니다. 현재 응용 프로그램은 데이터가 PHP에 직접 도달하기 때문에 작동하며 PHP는 json으로 지정된 들어오는 데이터를 구문 분석하지 않습니다. 콘텐츠 유형이 JSON으로 지정 될 때 요청 헤더의 콘텐츠 유형을 변경하십시오.

import express from 'express' 
var http = require('http') 
const redirectionRoutes = express.Router() 

redirectionRoutes.use(function(req, res, next) { 
    req.rawBody = '' 
    req.headers['content-type'] = 'text/plain' 

    req.on('data', function(chunk) { 
    req.rawBody += chunk 
    }) 

    req.on('end', function() { 
    next() 
    }) 
}) 

redirectionRoutes.post(/^\/update_services\/.*$/, function(request, response) { 
    var data = request.rawBody 
    var dataLength = data.length 
    var options = { 
     hostname: 'localhost', 
     port: 80, 
     path: request.path, 
     method: 'POST', 
     json: false, 
     headers: { 
     'Content-Type': 'text/plain', 
     'Content-Length': dataLength 
     } 
    } 

    var buffer = '' 
    var req = http.request(options, function(res) { 
     res.on('data', function(chunk) { 
     buffer += chunk 
     }) 
     res.on('end', function() { 
     response.send(buffer) 
     }) 
    }) 
    req.write(data) 
    req.end() 
}) 

그러나 nodejs (내 응용 프로그램)에서

는 몸 파서는 데이터를 구문 분석하고 JSON 아니다, 나는 오류가 점점 오전 :

SyntaxError: Unexpected token # in JSON at position 0

at JSON.parse (<anonymous>) 
at createStrictSyntaxError (../node_modules/body-parser/lib/types/json.js:157:10) 
at parse (../node_modules/body-parser/lib/types/json.js:83:15) 
at /Users/../node_modules/body-parser/lib/read.js:116:18 
at invokeCallback (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:224:16) 
at done (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:213:7) 
at IncomingMessage.onEnd (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:273:7) 
at emitNone (events.js:105:13) 
at IncomingMessage.emit (events.js:207:7) 
at endReadableNT (_stream_readable.js:1047:12) 

nodejs/body 파서가 들어오는 json을 구문 분석하지 않고 일반 텍스트로 함수에 들어가게하는 방법이 있습니까?

+0

'JSON.parse'가있는 코드를 보여줄 수 있습니까? – LMokrane

+0

어디서나 JSON.parse가 없으며 bodyParser @ user1851595도 제거했습니다. –

답변

0

해결되었습니다! 다른 페이지 라우터와 함께 앱 코드의 끝에이 모듈을 내보내고 있습니다. 그래서이 특정 라우터에서 사용하지 않으면 이전 라이브러리에서 호출 된 body-parser가 호출됩니다.