【问题标题】:[Passportjs][Angular5] No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access[Passportjs][Angular5] 请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问
【发布时间】:2018-10-23 08:40:40
【问题描述】:

我正在尝试将 Nodejs 后端 api 与 Angular 集成。我已经在后端应用程序上实现了 passpor-google、passport-github、passport-twitter 策略。

我的后端应用网址是http://localhost:3000 我的前端应用网址是http://localhost:4200

护照路线

authRouter.get('/github', passport.authenticate('github'));
authRouter.get(
  '/github/callback',
  passport.authenticate('github', {
    failureRedirect: 'http://localhost:4200/login',
  }),
  authController.sendJWTToken
);

当我从前端应用程序发送请求时,它给了我 CORS 错误

AuthService.ts

githubAuth(): Observable<LoginRsp> {
    return this.httpClient.get<LoginRsp>(
      `${environment.api_url}/auth/github`
    );
  }

我已经在我的 Nodejs 项目中添加了 CORS。我该如何解决这个问题,请帮助我

【问题讨论】:

    标签: node.js angular passport.js passport-google-oauth2 passport-github2


    【解决方案1】:

    你可以简单地写在你的html模板中

    <a href="http://localhost:3000/login/google">Google</a>
    

    而在后端你只需要拥有这个

    app.get('/login/google',  passport.authenticate('google', { scope: ['profile','email']}) );
    

    【讨论】:

      【解决方案2】:

      在 AuthService.ts 中只需使用 window.location.href='{environment.api_url}/auth/github'

      【讨论】:

        【解决方案3】:

        你可以像下面的图片那样做

        【讨论】:

          【解决方案4】:

          使用 cors 模块cors 否则使用 express cors 中间件express cors

          app.use(cors()); 在此之后的任何其他路线

          const users = require('./routes/users');
          

          或者尝试将 cors 中间件移到顶部

          【讨论】:

          • app.use(cors());
          • 您可能在错误的范围内使用了中间件,即确保在调用任何路由之前使用它
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-04-09
          • 2014-03-13
          • 2016-05-27
          • 2018-07-06
          • 2013-12-24
          • 2017-07-17
          • 2017-02-04
          相关资源
          最近更新 更多