body-parser:如何处理节点请求中收到的'&'?

时间:2018-10-22 14:07:15

标签: node.js json body-parser

当我将数据发送到我的nodeJS应用程序时,我的'&'字符出现了问题。

如果我发送此请求:

var str = JSON.stringify({ myValue: 'hello&world' });
fetch(myAPIpath, {
  method: 'post',
  body: `values=${str}`,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
});

然后我在Node应用程序中解析请求:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

我遇到以下错误:

  

SyntaxError:JSON输入意外结束

实际上,当我记录req.body.values时,我有这个:

  

{“ values”:“你好

您知道如何解决此问题吗?这是否意味着我无法在请求中发送'&'字符?

1 个答案:

答案 0 :(得分:0)

通常&是HTML编码为&amp的特殊字符。为了解决这个问题,可以通过来转义特殊字符。例如,在这里发送\&。当您也想在请求中的引号中发送内容时,也会看到此消息。