【发布时间】:2018-05-07 05:29:14
【问题描述】:
我应该将数据从应用程序发送到服务器,并且该应用程序的 post 方法是使用 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,body 解析器正在解析数据,因为它不是 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,而是以纯文本的形式进入函数。
【问题讨论】:
-
你能告诉我们
JSON.parse的代码吗? -
我在任何地方都没有 JSON.parse,我什至删除了 bodyParser @user1851595
标签: json node.js body-parser