【问题标题】:What is wrong with my req.body in Express that it wont let me parse JSON?我在 Express 中的 req.body 有什么问题,它不会让我解析 JSON?
【发布时间】:2018-05-30 20:45:52
【问题描述】:

我正在从我的前端向我从 Nodejs 提供服务的 Express 路由处理程序发出 ajax POST 请求。

我的数据正在以下列方式从发送端发送,并通过输出确认到控制台:

This data is sent from front.end: {"panReferenceID":"0987","walletAccountEmailAddressHash":"8907","clientWalletAccountId":"879","visaTokenScore":"0987","visaTokenDecisioning":"879","addressVerificationResultCode":"rty67u89i9o0","cvv2ResultsCode":"897","locale":"34567890","deviceInfo":{"deviceId":"hgjk","deviceLanguageCode":"890","osVersion":"ertyuio","osBuildID":"879","deviceIDType":"87","deviceManufacturer":"9876","deviceBrand":"897","deviceModel":"34567890","deviceName":"980","deviceNumber":"980","deviceLocation":"9876","deviceIpAddressV4":"789"},"encryptedData":"87"},http://localhost:3000/vtis/tokenRequestors/5/tokens/987/tokenChanged?eventType=TOKEN_CREATED&eventID=254

在后端,我得到了适当的请求对象。当我尝试使用以下语句将其记录到控制台时:

console.log("This is the request from the clientSide..." + JSON.stringify(req.body));

我在终端中得到了这个:

This is the request from the clientSide...{"{\"panReferenceID\":\"0987\",\"walle
tAccountEmailAddressHash\":\"8907\",\"clientWalletAccountId\":\"879\",\"visaToke
nScore\":\"0987\",\"visaTokenDecisioning\":\"879\",\"addressVerificationResultCo
de\":\"rty67u89i9o0\",\"cvv2ResultsCode\":\"897\",\"locale\":\"34567890\",\"devi
ceInfo\":{\"deviceId\":\"hgjk\",\"deviceLanguageCode\":\"890\",\"osVersion\":\"e
rtyuio\",\"osBuildID\":\"879\",\"deviceIDType\":\"87\",\"deviceManufacturer\":\"
9876\",\"deviceBrand\":\"897\",\"deviceModel\":\"34567890\",\"deviceName\":\"980
\",\"deviceNumber\":\"980\",\"deviceLocation\":\"9876\",\"deviceIpAddressV4\":\"
789\"},\"encryptedData\":\"87\"}":""}

为什么请求在引号前添加\???

我怀疑这是我问题的根源。我无法解析请求对象。我试过使用:

req.body["panReferenceID"] 

例如,要获取请求对象中的第一个数据项,但是,我在终端中得到“未定义”...

ajax 发布请求是怎么回事,为什么我无法解析它?

有人看到我在这里没有看到的错误???

谢谢..

编辑

这是我的客户端代码。当我在侧向后端之前将它输出到控制台时,它很好,在后端它看起来像它具有那个空值:

var deviceInfo = {
                'deviceId':deviceID, 'deviceLanguageCode': deviceLanguageCode, 
                'osType':osType, 'osVersion':osVersion, 'osBuildID':osBuildID,
                'deviceType': deviceType, 'deviceIDType':deviceIDType, 
                'deviceManufacturer':deviceManufacturer, 'deviceBrand':deviceBrand,
                'deviceModel':deviceModel, 'deviceName':deviceName, 'deviceNumber':deviceNumber,
                'deviceLocation':deviceLocation, 'deviceIpAddressV4':deviceIpAddressV4,
                'locationSource':locationSource,'tokenProtectionMethod':tokenProtectionMethod
            };

            // Need a JWE encryption mechanism for JWE data

            var requestPayload = {
                'panReferenceID':panReferenceID,
                'walletAccountEmailAddressHash':walletAccountEmailAddressHash,
                'clientWalletAccountId':clientWalletAccountId,
                'visaTokenScore':visaTokenScore,
                'visaTokenDecisioning':visaTokenDecisioning,
                'panSource':panSource,
                'addressVerificationResultCode':addressVerificationResultCode,
                'cvv2ResultsCode':cvv2ResultsCode,
                'consumerEntryMode':consumerEntryMode,
                'locale':locale,
                'deviceInfo':deviceInfo,
                'encryptedData':encryptedData
            }

            // reset form on submit
            // document.form["#tcnform"].reset()

            // async call to post form data to server to wait for response
            $.ajax({

                url: 'http://localhost:' + clientPort.toString() + '/vtis/tokenRequestors/' + inputTokenRequestorID + '/tokens/' + inputTokenReferenceID + '/tokenChanged?eventType=' + eventType + '&eventID=' + eventID,
                data: requestPayload,
                dataType: 'json',
                type: 'POST',
                Content-Type: 'application/json',

                success: function(data, textStatus){
                    console.log("DEBUG: Response from server: " + data);
                    console.log("Sent Token Create Notification: " + data);
                    console.log("This data is sent from front.end: " + this.data + "," + this.url);

                    // Need to get data from server based on tests and load to text field for copy by user






                },
                error: function(request, status, error){
                    var val = request.responseText;
                    console.log("Error in Ajax: " + val);
                }
            });

        }

【问题讨论】:

  • 您正在对字符串进行字符串化。你需要JSON.parse(req.body).panReferenceID
  • 抛出错误:SyntaxError: Unexpected token o in JSON at position 1
  • I can't get values from req.body node.js 的可能重复项更仔细地查看JSON.stringify() 的输出,您的对象实际上存储为字符串化 JSON 中的键,并且键的值是一个空字符串。这看起来像是客户端编码错误。
  • 澄清一下,在客户端,您似乎正在做这样的事情:var object = {}; object[JSON.stringify(data)] = ""; var body = JSON.stringify(object); 并发送。
  • 你可以使用body parser library

标签: javascript json node.js ajax express


【解决方案1】:
var bodyParser = require('body-parser')

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

// parse application/json
app.use(bodyParser.json())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多