【问题标题】:How to send string in get path (Node.js)?如何在获取路径(Node.js)中发送字符串?
【发布时间】:2021-06-08 11:13:46
【问题描述】:

用户可以为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}`);

【问题讨论】:

  • api.get(`get/${encodeURIComponent(search)}`);
  • 感谢@Chris G 和 ASDFGerte 它工作正常 :)

标签: javascript node.js mongodb mongoose get


【解决方案1】:

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

在前端 用户插入

 const word = 'sear%ch?';

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

const encodedWord = encodeURIComponent(word);

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

 const word = decodeURIComponent(encodedWord);

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-07
      • 2011-07-17
      • 2018-03-31
      • 2022-07-24
      • 2023-03-15
      • 2020-11-30
      • 2018-11-30
      • 2010-11-06
      相关资源
      最近更新 更多