reactjs - 如何使用 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
解决方案
确保将cors
中间件放在路由之前。
app.use(cors());
...
app.get('/user', ensureAuthenticated, function(req, res) {
res.json(req.user);
});
React 应用程序中使用的 url 也使用了https
方案。
推荐阅读
- java - Kotlin 等价于 Java `? 扩展`
- r - 在数字和 NA 列表中获取元素权重
- cluster-analysis - 如何在 Sklearn 中使用带有混合(分类和数字)数据的 silhouette_score?
- asp.net-mvc - (MVC) 我的共享 _Layout 中有一个搜索栏。它适用于其他视图,但不适用于 _Layout
- php - return redirect('/') 和 Redirect::to('/')->send() 有什么区别?laravel 中的函数
- snowflake-cloud-data-platform - 用于雪花的 Kafka 连接器不断失败
- node.js - 错误 node_modules/jest-diff/build/diffLines.d.ts(8,13): 错误 TS1005: '=' 预期。在嵌套js中
- amazon-web-services - 如何通过 AutoScaling 动态增加 AWS EMR 上的 ulimit?
- clone - 乐克隆物体没有沉没
- django - 如何在 Django 中以编程方式将用户添加到组