如何使用Express和React处理Passport身份验证中的网络错误

时间:2020-08-28 08:32:15

标签: reactjs express passport.js

我正在运行一个快递服务器,以启用使用护照的用户身份验证。运行快速URL时会获得用户信息,但无法使用axios从我的react应用程序中获取用户对象。我的React应用显示网络错误。

我尝试使用

const cors = require("cors");
app.use(cors())

Express app.js(以http://localhost:3000运行)

var Strategy = new OpenIDConnectStrategy({
  discoveryURL : discovery_url,
  clientID : client_id,
  clientSecret : client_secret,
  callbackURL : callback_url,
  skipUserProfile : true
},
  function(iss, sub, profile, accessToken, refreshToken, params, done) {
    process.nextTick(function() {
        profile.accessToken = accessToken;
        profile.refreshToken = refreshToken;
        done(null, profile);
    })
  }
)

passport.serializeUser(function(user, done) {
  done(null, user);
});
passport.deserializeUser(function(user, done) {
  done(null, user);
});

passport.use(Strategy); 
function ensureAuthenticated(req, res, next) {
  if(!req.isAuthenticated()) {
              req.session.originalUrl = req.originalUrl;
    res.redirect('/login');
  } else {
    return next();
  }
}

app.get('/user', ensureAuthenticated, function(req, res) {
  res.json(req.user);
});

我的Express应用程序在端口3000上运行,因此访问http:// localhost:3000 / user时可以看到用户对象

但是当我尝试在我的React应用程序中访问此网络时,我收到了网络错误。

我的反应成分是

import React from 'react';
import axios from 'axios';

export default class UserInfo extends React.Component {
  constructor() {
    super()
    this.state = {
      userinfo: {}
    }
  }

  componentDidMount() {
    axios.get('http://localhost:3000/user')
    .then(res => {
      const userinfo = res.data;
      this.setState({ userinfo });
    }).catch(err => {
      console.log("Fetch error", err)
    })
  }

  render() {
    console.log("User Info", userinfo);
    return (
      <React.Fragment>
        Name: {this.state.userinfo.name}
      </React.Fragment>
    )
  }
}

错误是

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (Reason: CORS request did not succeed).
Fetch error Error: Network Error

更改轴距后进行编辑

当我在mozilla开发人员工具中检查响应并检查了网络时。 API没有给出任何响应,然后将axios更改为

axios('https://localhost:3000/hello', { 
      method: 'get',
      withCredentials : true 
    })

然后,开发人员工具中的newtwok做出响应,而React应用程序崩溃,说Uncaught (in promise) Error: Network Error

1 个答案:

答案 0 :(得分:0)

确保在路由之前放置cors中间件。

app.use(cors());

...

app.get('/user', ensureAuthenticated, function(req, res) {
  res.json(req.user);
});

React应用中使用的网址也使用https方案。