【问题标题】:How do I handle a question mark being sent through a url?如何处理通过 url 发送的问号?
【发布时间】:2020-03-17 00:03:46
【问题描述】:

我正在使用 axios 向我的数据库发送一些字符串。我当前发送的内容是

1: Header -> the value can be anything such as "Who is Michael Scott?"
2: Body -> the value can be anything such as "Why do people quote Michael Scott a lot?"

我使用的axios命令是:

  axios.post(`/post/create/${Header}/${Body}`).then(result => {
    alert("Your post has been added!")
    console.log("Posted")
  }).catch(function (error) {
      // Output error
      console.log(error);
  });

url(地址栏)中的输出是:

http://my_ip_here:3000/api/v1/post/create/Who%20is%20Michael%20Scott?/Why%20do%20people%20quote%20Michael%20Scott%20a%20lot?/

由于问号,这最终给了我一个 404。我的问题是,如何处理作为 url 参数传递的字符串中的问号?

如果有帮助,我正在使用 React.js、Axios 和 Mysql。

【问题讨论】:

  • 您也可以传递您的数据并作为查询参数检索 /post/create?header='your header'&body='your body'

标签: mysql reactjs post axios


【解决方案1】:

您需要对它们进行 URL 编码。

在将它们的值传递给 axios 之前,请确保您运行 encodeURIComponent(myString)

也许是这样的:

axios.post(`/post/create/${encodeURIComponent(Header)}/${encodeURIComponent(Body)}`).then(result => {...}

【讨论】:

  • 谢谢!!我很惊讶我用谷歌搜索了多少,而且我一次也没有在任何地方看到 encodeURIComponent() !感谢布鲁诺的快速简短回复!
【解决方案2】:

我认为如果您使用此网址:/post/create/${Header}/${Body} 不是最佳做法。 如果您使用 post 方法,我建议您在正文中传递您的数据。

axios.post(`/post/create/`, {header: Header, body:Body}).then(result => {
    alert("Your post has been added!")
    console.log("Posted")
}).catch(function (error) {
    // Output error
    console.log(error);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    相关资源
    最近更新 更多