问题描述
我正在运行一个快递服务器,以启用使用护照的用户身份验证。运行快速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,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
解决方法
确保在路由之前放置cors
中间件。
app.use(cors());
...
app.get('/user',ensureAuthenticated,function(req,res) {
res.json(req.user);
});
React应用中使用的网址也使用https
方案。