【发布时间】:2019-03-14 02:24:17
【问题描述】:
我在 MERN Stack 上处理我的项目时遇到了问题。
我的 React 应用程序在端口 3000 上运行,并在 5000 上运行 api。我遇到的是,在使用 redux 添加 0auth 功能时,我收到类似“跨源请求被阻止:同源策略不允许读取远程资源”的错误here。(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。”
现在我的逻辑结构是这样的:
我已经为护照定义了谷歌策略。在快速路由 (http://localhost:5000/api/user/auth/google) 和回调 url (http://localhost:5000/api/user/auth/google/callback) 中定义路由。现在,当我直接访问“http://localhost:5000/api/user/auth/google”时,我可以完成流程,但是当我通过 react 应用程序中的 reducer 调用它时,我遇到了上述错误。
我的代码如下:
// Routes
router.get(
"/auth/google",
passport.authenticate("google", {
scope: ["profile", "email"]
})
);
router.get(
"/auth/google/callback",
passport.authenticate("google", {
failureRedirect: "/",
session: false
}),
function(req, res) {
var token = req.user.token;
console.log(res);
res.json({
success: true,
token: 'Bearer ' + token,
});
}
);
//Reducers Action
export const googleLoginUser = () => dispatch => {
axios
.get('api/users/auth/google')
.then((res) => {
//save to local Storage
const {
token
} = res.data;
// Set token to local storage
localStorage.setItem('jwtToken', token);
//set token to auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
console.log(decoded);
// set current user
dispatch(setCurrentUser(decoded));
})
.catch(err => {
console.log(err);
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
}
)
}
【问题讨论】:
标签: javascript reactjs express oauth cors