【问题标题】:Angular cors error while accessing google auth from express js从 express js 访问 google auth 时出现 Angular cors 错误
【发布时间】:2021-11-18 12:06:48
【问题描述】:

错误:从源“http://localhost:4200”重定向到“http://localhost:5000/auth/google”)已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于请求的资源上。

即使我在服务器中使用 cors 模块,我也会收到此错误。

const cors = require('cors')
app.use(cors())

也试过这个而不是 cors

app.use((req, res, next) => {
    console.log("entered cors")
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET , PUT , POST , DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type, x-requested-with");
    next();
})

我的角度服务代码

当我点击使用谷歌按钮登录时,此服务方法将被执行

addGoogleUser():Observable<any>{
  const headers = new HttpHeaders()
  headers.set('content-type','application/json')
  return this.http.get("http://localhost:5000/auth/google",{headers:headers});
}

【问题讨论】:

  • 您不必在有角度的一侧设置这些标题.. 这可能实际上会导致 CORS 问题..
  • 你修好了吗?
  • 删除 Angular 中的标题也没有解决

标签: node.js angular express cors passport-google-oauth2


【解决方案1】:

试试下面 -

app.get('/auth/google', cors(), (req, res) => {
        // your get code
 });

【讨论】:

  • 我试过了,但又出现同样的错误
  • 没有完整代码很难看出问题。您可以将您的代码上传到 stackblitz 并分享吗?
  • 我需要上传整个项目或服务器文件和角度服务吗?
  • 检查 server.js 和 angular-frontend/src/app/services/auth.service.ts
【解决方案2】:

在您的快递服务中:

res.header("Access-Control-Allow-Origin", '*');

或者

res.header("Access-Control-Allow-Origin", "http://localhost:4200");

并确保在拨打其他路线之前先拨打app.use((req, res, next) =&gt; {}

【讨论】:

  • 试过但没用
  • 当将链接直接粘贴到浏览器中时它正在工作 ihttp://localhost:5000/auth/google 可以访问谷歌帐户信息,它不能从角度工作。由于 cors 政策而被阻止
  • 好的,还要确保您的请求和端点与您的 api 所期望的相匹配。有时这可能是个问题,您的服务器不知道如何响应您的请求。
猜你喜欢
  • 2017-06-03
  • 2017-04-24
  • 2020-03-05
  • 2017-06-20
  • 2017-09-23
  • 1970-01-01
  • 2020-08-13
  • 2019-12-25
  • 2019-06-28
相关资源
最近更新 更多