如何使用 Axios & 传递 Header JWT Token反应? [英] How to pass Header JWT Token with Axios & React?

查看:25
本文介绍了如何使用 Axios & 传递 Header JWT Token反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 React、Express、MongoDB 制作 Web 应用程序.

I make web application with React, Express, MongoDB.

而且,我想通过标头传递 jwt 令牌.

And, I want to pass jwt token with header.

但是,我通过了,得到 401 错误(未经授权).

But, I pass it, get 401 error (Unauthorized).

在登录 actions.js 中:

In login actions.js :

export function login(username, password) {
return function(dispatch) {
  axios
  .post(`${API_URL}/auth/login`, { username, password })
  .then(res => {
    dispatch(loginSuccess(res.data, username));
    const token = res.data.token;
    axios.defaults.headers.common["Authorization"] = token;
    history.push("/");
  })
  .catch(err => {
    if (err.response.status === 401) {
      dispatch(loginFailure(err));
    }
  });
 };
}

而且,在我的 post.js 服务器中:

And, In my post.js in server :

getToken = function(headers) {
  if (headers && headers.authorization) {
    var parted = headers.authorization.split(" ");
      if (parted.length === 2) {
       return parted[1];
      } else {
       return null;
      }
    } else {
     return null;
    }
 };
...
// Save Post
router.post("/", passport.authenticate("jwt", { session: false }), 
 function(
  req,
  res,
  next
  ) {
 var token = getToken(req.headers);
 if (token) {
   Post.create(req.body, function(err, post) {
     if (err) return next(err);
      res.json(post);
     });
   } else {
    return res.status(403).send({ success: false, msg: "Unauthorized." });
   }
});

我该如何解决?+ 登录成功

How I do fix it? + Login is success

推荐答案

首先,当您登录并将用户名和密码发送到后端时,您会得到 token_id 作为响应.现在尝试在 session_storage 中存储令牌并重定向到您想要的页面.现在你在你的愿望页面中获取 token_id 并像这样存储一个变量..

First of all when you login and send username and password to backend then in response you get token_id. now try to token store in session_storage and redirect to your desire page. now you take token_id in your desire page and store one variable as like..

let user = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id;

现在您有了令牌并传入标头并在响应中获取数据

now you have token and pass in the header and get data in response

const api = `your api here`
axios.get(api, { headers: {"Authorization" : `Bearer ${token}`} })
        .then(res => {
            console.log(res.data);
        this.setState({
            items: res.data,  /*set response data in items array*/
            isLoaded : true,
            redirectToReferrer: false
        })

注意:你应该在初始 setState 中设置空白项数组,就像

note : you should set blank items array in initial setState as like

this.state={
            items:[],
            isLoaded: false,
            redirectToReferrer:false,
            token:''
        }

这篇关于如何使用 Axios & 传递 Header JWT Token反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆