【问题标题】:Passing request parameters on an API fetch Request在 API 获取请求上传递请求参数
【发布时间】:2021-09-24 13:51:35
【问题描述】:

如何将参数传递给获取请求?我有这个 api 调用来获取登录用户的用户名。如何将返回的结果作为请求参数传递给另一个 fetch 请求路由?

//Gets logged in user's username

async function getProfile(){
  try {
    const response = await fetch(`${SUMMIT_API}/users/myprofile`,{
      method: 'GET',  
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${myToken}`
      },
    })
    const data = await response.json();
    console.log(data)
    return data.profile
  } catch (error) {
    console.log('Oops Something Went Wrong! Could not get that user profile.');
  }


} 

从上面获取的结果:

//Request parameters is the logged in user's username in the route retrieved from above fetch request


async function userChannel(){
  try {
    const response = await fetch(`${SUMMIT_API}/users/myprofile/**${username}**/channel`,{
      method: 'GET',  
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${myToken}`
      }
    })
    const data = await response.json();
    console.log(data)
    return data.profile;
  } catch (error) {
    console.log('Oops Something Went Wrong! Could not render userChannel');
  }


}

如何从第一个请求传递到第二个请求的信息?

【问题讨论】:

  • 你只是想在userChannel开头做var profile = await getProfile(); var username = profile[0].username;吗?
  • 不确定,我会尝试,我只想将返回的用户名作为参数传递给另一个 fetch。如何从结果中提取它?
  • 这正是我所需要的,谢谢!!

标签: javascript parameter-passing fetch-api


【解决方案1】:

由于您想要的信息似乎是由您的async function getProfile 提供的,因此您似乎只需要await getProfile() 并提取必要的信息即可:

var profile = await getProfile();
var username = profile[0].username;

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2018-11-06
    • 2021-02-01
    • 2016-07-11
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多