无法读取请求正文但可以打印

Can't read body of request but can print it

我正在拔头发。根据 http 请求,我可以打印 body 对象但无法访问其内容。

所以我正在从网络发送这样的请求:

  return fetch('https:xxxxxxx/xxxx', {
            method: 'post',
            body: JSON.stringify(saleObject),
            headers: {
              'Accept': 'application/json',
              'contentType':"application/json",
               'dataType':"json",
            }
          }).then(function(res) {
            return res.json();
          }).then(function(data) {
            return data.orderID;  
          });
        }

在我的服务器(nodejs express Firebase)上,我试图以多种方式阅读它:

exports.payPalIntent = functions.https.onRequest(async(req, res) => {
return cors(req, res, async () => {
 
   console.log("req.body",req.body);  //this print AN OBJECT, A REAL OBJECT NOT A STRING
   console.log("req address",req.body.address); //=undefined, there is address property inside which

   return res.send(200);
 });

所以,第一个打印这个:

req.body {"address":{"city":"some city","zip":"345334","area":"USA","street":"Hai 13", ........

第二个说Cannot read property 'address' of undefined

当然,我也试过 JSON.stringify(req.body),它打印了一个我无法访问的字符串对象。

你如何访问这个对象?

JSON.stringify 将 JavaScript 对象转换为 JSON 字符串。你已经有一个 JSON 字符串,你想把它转换成一个 JavaScript 对象,所以使用相反的方法:JSON.parse(req.body)。然后您应该能够使用点运算符访问属性。