【发布时间】:2019-03-30 20:41:03
【问题描述】:
由于某种原因,我无法在浏览器中存储 cookie。
这是我第一次使用 React 和 NodeJS
我的 React 应用程序正在 localhost:3000 上运行,而 NodeJS 应用程序正在 localhost:8080 上运行
same happens to be this 的 Git 存储库
所以,我可以成功登录,将凭据存储在数据库中,并可能进行序列化和反序列化。
我没有分享 Google Strategy 以及序列化和反序列化的代码,因为我相信这个问题不存在(如果你认为你需要查看它click here
此 Google 重定向 returns at following callback
router.get("/google/callback", passport.authenticate('google', { failureRedirect: "/", session: false }), (req, res) => {
res.redirect("http://localhost:3000/")
})
在我的server.js(主文件,我通过执行node server.js 启动节点服务器),我这样做是为了存储cookie
app.use(cors({
credentials: true,
origin: ['http://localhost:3000'] // here goes any Frontend IP Adress
}))
//We are setting cookie here
app.use(cookieSession({
maxAge: 24*60*60*1000, //cookies is valid for a day
keys: ['fgfhfjhfad']
}))
app.use(passport.initialize())
app.use(passport.session())
然后当我在my react frontend 中这样做时
componentWillMount() {
axios.get("http://localhost:8080/", {withCredentials: true}).then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
我的localhost:3000/ 看起来像这样
app.get("/", (req, res) => {
if (req.user) {
if (req.isFormFilled) {
res.redirect("http://localhost:3000/home")
} else {
res.json(req.user)
}
} else {
res.json("user does not exsist")
}
})
它总是记录res.json("user does not exsist"),但如果我直接在浏览器中访问 localhost:3000,我可以看到我的 req.user [参见:更新下面的问题]
PS;我正在浏览器中启用跨域请求
[问题:]谁能帮我找出我可能做错了什么?
[更新:] 看来我们可能遇到了 crocs 错误,我已经更改了我的代码,我在前端收到了这个错误
在 'localhost:8080' 从源访问 XMLHttpRequest 'localhost:3000' 已被 CORS 策略阻止: 响应中的“Access-Control-Allow-Origin”标头不能是 当请求的凭据模式为“包含”时,通配符“*”。这 XMLHttpRequest 发起的请求的凭证模式是 由 withCredentials 属性控制
如果我在 axios 请求中删除 {withCredentials: true},则上述错误会消失,但随后会在 response.data 中记录 user does not exsist
【问题讨论】:
-
虽然其他答案在技术上可能是正确的,但更基本的问题是为什么您的前端和后端在不同的端口上运行。您遇到的 CORS 错误是浏览器试图阻止网站从呼叫一个未知的,可能是恶意的外部实体。您通常希望两个服务在同一个端口上运行,以模拟它们源自同一个域。
-
@RyanVillanueva 请在此处分享您的答案stackoverflow.com/questions/52996320/using-nodejs-with-react
标签: javascript node.js reactjs passport.js