简体   繁体   中英

How do send my JWT token when I make a GET/POST request to the api endpoint through UI?

So I created Nodejs api and I was accessing it using postman up until now. But now I wanted to create the forntend. In the api when the user logs in he will get a JWT token and when accessing protected routes he needs to send the JWT token. I was sending the token in header using postman. How can I do that through frontend?

Inside login function, on success, use callback function with jwt parameter to call localStorage.setItem('userToken', jwt) . This will put your jwt inside user's browsers local storage. Then, if you are using for example axios for backend calls you should add interceptor that will on every request send jwt as well. Something like this

axios.interceptors.request.use(async () => {
  request.headers.common.Authorization = `bearer ${window.localStorage.getItem('userToken')}`;
  return request;
}, err => Promise.reject(err));

So, it is not going to be exactly like this, but something similar that suits your needs

On Login success store the token in local storage localStorage.getItem('token')

Then pass the token to the api in header by fetching it from localStorage

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