简体   繁体   中英

API call (fetch) with user token through Javascript (React.js)

how are you guys doing??

I'm trying to fetch data (in React with JS) from a website X (that has cors-enabled) but need first to get a user token from a website Y and I don't know how to figure that out. Somehow I think that I have to get the user token from Y, save it in a variable and add it as a header on the other call but I'm kinda lost with the GET/POST methods.

By now what I have is this but somehow doesn't work, I think I'm not sending properly the head or making the actual calls correctly:

getToken(){
  const url = 'websiteOfTheToken';
  const response = await fetch(url);
  const data = await response.json();
  this.setState({
    userToken: data.image
  });
}

And:

getData(){
 const response = await fetch('websiteOfTheData', {
    method: 'POST', 
    mode: 'no-cors', 
    cache: 'no-cache', 
    credentials: 'same-origin',
    headers: {
      'accept': 'application/json',
      'Content-Type': 'application/json'
    },
    redirect: 'follow', 
    referrerPolicy: 'no-referrer',
    body: JSON.stringify({
      title: '' // I don't know what is this doing
    }) 
    }).catch( error => {
    console.log('Error fetching and parsing data ', error)
    });

  this.setState({
    data: response.json()
  });
}

Thank you in advance!!

A few things I want to say / ask about:

  1. Typically you get the token after a successfull login, so a standard request for a token would be a post request with the user data.
  2. An await in javascript works only inside async functions, read about it.
  3. The most common practice for handling api responses (Promise) is to use then-catch blocks, read about it.
  4. A typical JWT header you need to attach to your requests looks like this: "Authorization": "Bearer theactualtoken1234" .
  5. The body of the fetch post request is the actual data you're sending to the server. So its contents are totally arbitrary - I also don't have an idea what this "title": "" is doing...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM