2017-11-23 7 views
0

アプリからサーバーにデータを送信する予定で、そのアプリケーションの投稿メソッドがコンテンツタイプapplication/jsonを使用して作成されていますが、プレーンテキストです。このヘッダーを変更するようにアプリを更新することはできません。現在のアプリケーションは、データがPHPに直接渡されるため、PHPは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として指定されているように、ボディパーサーはデータを解析しているし、それは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が呼び出されています。

関連する問題