react api 调用中的路径变量

path variables in react api call

我有一个 API 可以响应 Postman 中的 API 调用,如下所示:

身材刚刚好

"username": "bobmarley"

如何在我的 React/Next 项目中复制它?

这是我目前拥有的:

export async function getUser(data) {
  
  const response = await fetch(`http://localhost:4000/users/:username`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
  })

  var response_data = await response.json();

  return(response_data);
}

我怎样才能像在 Postman 中一样传递这些路径变量?

更新

我实施了建议的更改,但遇到了问题:

export async function getUser(data) {

  const username = data
  const response = await fetch(`http://localhost:4000/users/${username}`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({username: username})
  })
  var response_data = await response.json();
  
  return(response_data);
}

这会引发错误:

http://localhost:4000/users/bobmarley 404 (Not Found)

不确定该怎么做?

更新 2

我将 POST 更改为 GET,但出现此错误:

TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

我在邮递员中使用下面的正文进行了 GET,并且工作正常。

{
    "username": "bobmarley"
}

:username 称为请求参数,当您在这些框中指定值时,Postman 会在后台为您解析它。

但是,使用 React,您需要在提取中指定用户名的值 URL。

所以它应该是这样的:

http://localhost:4000/users/bobmarly

与此相反

http://localhost:4000/users/:username

因此,如果您在 data 中有 username,则您要传递给 getUser() 函数,然后使用 URL 中的模板字符串在 URL 中指定它 javascript.

像这样

const username = data.username || 'bobmarley';

const response = await fetch(`http://localhost:4000/users/${username}`, {
  ...
})

您必须在字符串本身中传递它,例如:

export async function getUser(data) {

  const username = data.username //fake, but something like that i guess
  
  // and then use template string notation `regular string ${jsInterpolation}`
  const response = await fetch(`http://localhost:4000/users/${username}`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(data)
  })
  var response_data = await response.json();

  return(response_data);
}

其他人都知道了,就piggy-backing这里吧。

您的 API 应该正在解析查询字符串。也就是说,看起来您已经将 API 设置为 需要 来查看查询字符串的 /:username 部分。或者,您可以在 body 中传递它,但这超出了您的问题范围。这是一个示例,考虑到您的限制条件。

export async function getUser({ username = 'bobmarley', ...rest }) {
  
  const response = await fetch(`http://localhost:4000/users/${username}`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(rest)

  });

  const response_data = await response.json();

  return response_data;
}

除非您在 body 中传递其他数据,否则您可以将数据参数解构为它的 username 属性。但是,如果您 正在 传递或需要其他 body 数据,请确保您的 API 端点也设置为处理该类型的数据(我离开了JSON.stringify部分,供参考)。