简体   繁体   English

React + Passport.js

[英]React + Passport.js

TL;DR I'm making a MERN app and want to access the passport user from React. TL; DR我正在制作一个MERN应用程序,并希望从React访问护照用户。 How? 怎么样?

I'm trying to make a simple to-do app with the MERN stack and can't get user auth down. 我正在尝试使用MERN堆栈制作一个简单的待办应用,并且无法使用户身份验证失败。 I'm using React on the front end with a proxy to an express api. 我在前端使用React并使用Express api的代理。 I want to grab the req.user object from React so I can update the navbar based on whether the user is logged in or not. 我想从React那里获取req.user对象,这样我就可以根据用户是否登录来更新导航栏。 When I post to /api/login I can log the user object from the api route. 当我发布到/api/login我可以通过api路由记录用户对象。

React login form: React登录表单:

class Login extends Component {
//..
  async login(event) {
    event.preventDefault();
    await api.login({
      username: this.state.username,
      password: this.state.password
    });
    this.setState({
      username: '',
      password: ''
    });
  }
//..
}

Axios: Axios:

export async function login({username, password}) {
  axios.post('/api/login', {username, password});
}

Server: 服务器:

router.post('/login', passport.authenticate('local'), helpers.login);

exports.login = (req, res) => {
  res.json({ message: 'You have been logged in!' });
};

From this exports.login function I can console.log(req.user) but when I try to access the user from any other route it is undefined. 从这个exports.login功能,我可以console.log(req.user)但是当我尝试从任何其他途径访问用户这是不确定的。

Here's what I want to do: 这是我想做的:

React: 反应:

class App extends Component {
//..
  componentDidMount() {
    this.isLoggedIn();
  }

  componentDidUpdate() {
    this.isLoggedIn();
  }

  async isLoggedIn() {
    const user = await api.isLoggedIn(); 
  }
//..
}

Which will make a request that returns the user object. 它将发出一个返回用户对象的请求。

I somewhat understand how the proxy may get in the way and how the session works but the pieces haven't clicked yet. 我有点理解代理可能会遇到的麻烦以及会话的工作方式,但是片段尚未被点击。 Hoping someone can help me out. 希望有人可以帮助我。

EDIT So um... the problem just kinda went away. 编辑那么...问题就解决了。 I'll update if something breaks again. 如果有什么再次出现问题,我会更新。

Possible duplicate here But to check out the accepted answer by @Molda there was a link to the Github Repository that gave a very good example of how to handle the authentication on the client. 这里可能重复但是要查看@Molda接受的答案,有一个指向Github存储库的链接,该链接提供了一个很好的示例,说明了如何在客户端上处理身份验证。 You will have to change some of the token authentication to the user that is returned from the server when you login. 登录时,您必须将某些令牌身份验证更改为从服务器返回的用户。

Basically you need to store the user somewhere on the client like the browsers local storage. 基本上,您需要将用户存储在客户端的某个位置,例如浏览器的本地存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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