【问题标题】:reactjs display user info from passportjs authreactjs显示来自passportjs auth的用户信息
【发布时间】:2017-10-02 07:26:30
【问题描述】:

我使用护照在我的反应样板应用程序的服务器中进行身份验证,但我不确定如何从我的服务器端获取 req.user 到 reactjs...

我应该改变这个

app.get('*', (req, res) => {
    fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
      if (err) {
        res.sendStatus(404);
      } else {
        res.send(file.toString());
      }
    });
  });

我很不确定该怎么做,尤其是因为我之前没有使用过 reactjs

【问题讨论】:

  • 你在使用body-parser库吗?
  • 在服务器端我是

标签: node.js reactjs passport.js


【解决方案1】:

你必须添加一个路由(在你发送的代码之前)来检索它,像这样:

app.get('/userDetails', (req, res) => res.json(req.user))

还有一个警告:你的用户对象可能有一些你不应该发送给客户端的字段,所以最好在发送响应之前删除它们:

app.get('/userDetails', (req, res) => {
  const { user } = req.body
  delete user.password
  res.json(user)
})

然后您需要通过向后端发出请求来获取数据。一种可能的实现是:

class SomeComponent {
  state = { user: null }
  componentDidMount () {
    fetch('/userDetails')
    .then(res => res.json())
    .then(user => {
      // do something with the data
      console.log(user)
      this.setState({ user })
    })
  render () {
    const { user } = this.state
    return (
      <span>{user ? user.firstName : 'No user data'}</span>
    )
  }
}

【讨论】:

  • 我会试试这个,我使用 oauth 没有密码
  • 我现在如何在 reactjs 中访问这些用户详细信息?
  • @strykes 我还为您添加了一些反应代码,展示如何在客户端检索该数据
  • 基本上,在这种情况下,应用程序分为两部分:后端,与数据库交互并通过 JSON API 提供数据,以及反应客户端应用程序,然后使用后端 API 检索必要的数据。
  • FWIW 您不需要进行单独的 API 调用(请参阅我的回答)。
【解决方案2】:

如果您使用 templating engine 将数据嵌入视图非常简单。

这是一个使用 pug 的示例:

views/index.pug

doctype html
html
    body
        h2 Page
        script.
            window.user = '#{JSON.stringify(user)}'

server.js

app.use('view engine', 'pug');
...
app.get('*', (req, res) => {
    res.render('index', {
         user: {
             id: 1,
             name: 'Joe Bloggs'
             ...
         }
    }); 
});

【讨论】:

  • 我正在使用 react.js
  • 你能修改它以在我的原始帖子中使用我的 app.get 吗?
  • @strykes 我已经为您提供了一个示例,说明如何将其与默认路由一起使用(至少使用 pug)。还有其他模板引擎,如果您不确定它们是如何工作的,我建议您阅读文档以了解它们。总而言之,您需要将 index.html 转换为 index.pug
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 2018-12-10
  • 1970-01-01
  • 2021-04-06
相关资源
最近更新 更多