【问题标题】:Pass variables in url path to fetch GET request在 url 路径中传递变量以获取 GET 请求
【发布时间】:2021-08-29 06:18:45
【问题描述】:

我在下面有这个获取请求,以及变量 data_type 和 data_subtype。我想分别在 :type 和 :subtype 的位置传递 data_type 和 data_subtype 的值,而不是在其中实际写入变量值。

fetch('http://localhost:3000/feature/type/:type/subtype/:subtype,{
    method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
}).then(response => response.text())
.then(data => {
        console.log(data);
})
.catch(err => {
          console.log(err);
});

【问题讨论】:

  • 那么,您是在问我们如何在 JS 中将字符串连接在一起?
  • 谢谢@blex!我理解你的意思,一个简单的串联就可以了!

标签: javascript url path get fetch


【解决方案1】:

您可以替换为 URL 中的变量值。 例如。

const data_type = 'data Type' 
const data_subtype = 'data subtype
fetch(`http://localhost:3000/feature/type/${data_type}/subtype/${data_subtype}`,{
    method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
}).then(response => response.text())
.then(data => {
        console.log(data);
})
.catch(err => {
          console.log(err);
});

【讨论】:

  • 感谢@junkie 的帮助,这个方法也有效。
【解决方案2】:

作为扩展@junkie 的答案,您应该将您的 url 请求放在字符串文字中,以便您可以在其中使用有条件地替换值而不实际在其中写入值的变量,因此只需定义并替换它们。

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多