Node.js 中的正文解析未转义请求正文中的新行字符? JSON

Body-parse in Node.js not escaping new line chars in request body ? JSON

我正在创建一个基本的反向代理来将客户端请求传递到远程服务器。

所以我将 body-parse 与 express.js 用于 Node 服务器以允许我传递 body。

但是 JSON 中包含换行符和额外的大括号。

客户端

{
   "lastRefreshedDateTime" : "2015-05-24",
   "uid" : "1232141451"
}

服务器端

{
    '{
        \r\n"lastRefreshedDateTime": "2015-05-24",
        \r\n"uid
": "1234567124321"\r\n
    }\r\n': ''
}

Node.js代码

        var express = require('express');
    var http = require('request');
    var path = require('path');
    var url = require("url");
    var bodyParser = require("body-parser"); //this is required in express 4.x to output the contents of the client request body
    var app = express(); //start express server

    // parse application/x-www-form-urlencoded
//app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser().json())
    // POST - getLocationData
    app.post('/getLocationData', function (request, response)
    {
        console.log("Request for /getLocationData");
        forwardRequest(request, response, "getLocationData", "POST", true);
    });


    app.listen(8080);

    function forwardRequest(request, response, serviceName, requestMethod, isJSON)
    {

        console.log("Making request to EAS for " + serviceName + ":");
        console.log(request.body); //json is fubar!

    };

我试过自己去掉换行符,还是没有解决多出来的大括号和倒排的问题

您需要 body-parser 但您似乎从未使用过它..

app.use(bodyParser());

把这个放在要求之后

丑化客户端的json。在发送字符串之前删除漂亮的打印,应该可以解决问题。

在客户端使用JSON.stringify,在服务器端使用JSON.parse

edited to reflect comments

关于您关于 JMeter usage 的问题,您遇到的问题实际上可能是由 Jackson 或其他 Java JSON 库引起的。 将您的内容类型编码设置为 UTF-8 通常可以完全解决问题。