我在 CORS 方面遇到了很多麻烦。我在我的域上部署了一个 Express 服务器,目前正在 localhost:3000 上本地开发一个 React 应用程序。
当我尝试使用 Passport.js 注销后重定向时,我遇到了这三个与 cors 相关的错误。
我尝试了多种组合来尝试启动并运行它,但根本无法使重定向正常工作,而且我不确定我在这里缺少什么。想知道这是否是 Next 开发服务器的问题?任何建议将不胜感激!
Access to fetch at 'http://localhost:3000/login/' (redirected from 'https://api.invoice-app.naughty-cat.com/authentication/logout') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET http://localhost:3000/login/ net::ERR_FAILED
TypeError: Failed to fetch
at handleLogoutClick (NavBar.jsx:43:11)
at HTMLUnknownElement.callCallback (react-dom.development.js:17629:30)
at Object.invokeGuardedCallbackImpl (react-dom.development.js:17667:30)
at invokeGuardedCallback (react-dom.development.js:17729:39)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:17741:35)
at executeDispatch (react-dom.development.js:27186:13)
at processDispatchQueueItemsInOrder (react-dom.development.js:27206:21)
at processDispatchQueue (react-dom.development.js:27215:17)
at dispatchEventsForPlugins (react-dom.development.js:27223:13)
at eval (react-dom.development.js:27378:24)
at batchedUpdates$1 (react-dom.development.js:21180:24)
at batchedUpdates (react-dom.development.js:24349:24)
at dispatchEventForPluginEventSystem (react-dom.development.js:27377:13)
at dispatchEvent (react-dom.development.js:25416:17)
at dispatchDiscreteEvent (react-dom.development.js:25392:17)
这是我的cors配置:
app.use(
cors({
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true
})
);
这是我在 Passport.js 注销后进行重定向的路线:
authRouter.post('/logout', (req, res, next) => {
req.logout(function(err){
if(err){
return next(err);
}
res.redirect('http://localhost:3000/login/');
})
});
这是我失败的获取:
fetch(`https://api.invoice-app.naughty-cat.com/authentication/logout`,
{
method: "POST",
redirect: 'follow',
withCredentials: true,
}).catch(err => console.log(err));
编辑:所以当我更多地处理这个问题时,我发现如果只是使用 href 设置为 html 中的链接并且一切都按预期工作,则登录路由将起作用。但是当我将其更改为使用获取(如上面的注销示例)时,它会收到相同的错误。我需要使用提取,因为注销路由必须是发布请求。我在这里缺少什么想法吗?
编辑2:我已经测试了不涉及oauth的正常路由,它们都能够正常通过。只有 oauth 路由抛出此错误。
好吧,经过一番挖掘后发现,使用 fetch 或 axios 会导致一些常见问题。最后,我能够使用以下代码启动并运行。并不完全理想,但它非常干净和高效。登录的 get 请求可以是任何类型的链接等,但我必须发出 post 请求来注销表单,以便它可以这样发送。
<Link
href={`https://api.invoice-app.naughty-cat.com/authentication/github`}
className="bodyText font-bold hover:text-purple"
onClick={() => {
setIsProfileOpen(!isProfileOpen);
}}
>
Sign in with Github
</Link>
<form
action="https://api.invoice-app.naughty-cat.com/authentication/logout"
method="POST"
>
<button
type="submit"
className="bodyText font-bold hover:text-purple"
onClick={() => setIsProfileOpen(!isProfileOpen)}
>
Sign Out
</button>
</form>