首页 > 解决方案 > 如何使用 Express 和 React 处理 Passport 身份验证中的网络错误

问题描述

我有一个快速服务器正在运行以启用使用护照的用户身份验证。我在运行快速 URL 时获取了用户信息,但我无法使用 axios 从我的反应应用程序中获取用户对象。我的 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);
});

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

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

我的反应组件是

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

更改 axios 后编辑

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

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

然后开发者工具中的newtwok给出响应,react应用程序崩溃说Uncaught (in promise) Error: Network Error

标签: reactjsexpresspassport.js

解决方案


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

app.use(cors());

...

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

React 应用程序中使用的 url 也使用了https方案。


推荐阅读