如何在获取路径Node.js中发送字符串?

问题描述

用户可以为 search 输入不同的字符。因此,当用户输入字符时会出现错误,例如/ 要么 %。如何在 get 查询中发送变量 search

router.get('/get/:search',(req,res) => {
    Label.aggregate(pipeline)
        .then(result => {
            res.json(result);
        })
        .catch(err => {
            res.status(500).send(err);
        });
});

在前端:

api.get(`${'get'}/${search}`);

解决方法

为此javascript有标准函数encodeURIComponent(param),decodeURIComponent(encodedParam)

在前端 用户插入

 const word = 'sear%ch?';

在将单词附加到 api url 之前,需要对其进行编码。

const encodedWord = encodeURIComponent(word);

从url获取searchWord后后端需要解码。

 const word = decodeURIComponent(encodedWord);
,

我在评论中使用了@Chris G 和@ASDFGerte 的解决方案 api.get(`get/${encodeURIComponent(search)}`);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent