简体   繁体   English

CORS 问题 - Angular 8 - NodeJS 和 ExpressJS

[英]CORS Issue - Angular 8 - NodeJS & ExpressJS

I've tried a few different solutions from other threads and suspect I'm missing something small here.我尝试了其他线程的一些不同解决方案,并怀疑我在这里遗漏了一些小东西。

I have an AngularJS 8 application, running on Node 10 with ExpressJS.我有一个 AngularJS 8 应用程序,使用 ExpressJS 在 Node 10 上运行。 Having some CORS issues when trying to access Google's People API.尝试访问 Google 的 People API 时遇到一些 CORS 问题。

Access to XMLHttpRequest at 'https://developers.google.com/people/api/rest/v1/people.connections' from origin 'http://app.x.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

My frontend code looks like:我的前端代码如下所示:

    return this.httpClient.get(this.API_URL, {
      headers: new HttpHeaders({
        Authorization: `Bearer ${authtoken}`,
        'Access-Control-Allow-Origin': 'http://localhost:4200',
        'Access-Control-Allow-Credentials': 'true',
      })
    });
  }

My server side code:我的服务器端代码:


let express = require('express'),
  path = require('path'),
  cors = require('cors');
// Connecting mongoDB
var compression = require('compression')
var session = require("express-session");

let app = express();
app.use(session({
  secret: '#######################',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));
app.use(compression())
app.use(cors());

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});


/*var corsOptions = {
  origin: '*',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
*/

app.use(express.static(path.join(__dirname, 'dist/###')));
app.use('/*', express.static(path.join(__dirname, 'dist/##')));
// Create port
const port = 8080;
const server = app.listen(port, () => {
  console.log('Connected to port ' + port)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});


app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  {
    res.status(err.statusCode).send(err.message);
  }


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

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  if (!err.statusCode) err.statusCode = 500;
  {
    res.status(err.statusCode).send(err.message);
  }


  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});


As you can see, I've tried a couple of different approaches.如您所见,我尝试了几种不同的方法。 Would appreciate any suggestions.将不胜感激任何建议。

Thank You谢谢你

Fixed the issue in another way.以另一种方式修复了该问题。 Using the Gapi library (javascript: https://github.com/google/google-api-javascript-client/blob/master/docs/reference.md ) and its Auth, I was able to login, get the JWT and use that as a credential.使用 Gapi 库(javascript: https : //github.com/google/google-api-javascript-client/blob/master/docs/reference.md )及其身份验证,我能够登录,获取 JWT 并使用那作为凭证。

    const googleUser = await googleAuth.signIn();

    const token = googleUser.getAuthResponse().id_token;

    const credential = firebase.auth.GoogleAuthProvider.credential(token);
    await firebase.auth().signInAndRetrieveDataWithCredential(credential);

    return googleUser;

Using that credential login to firebase.使用该凭据登录到 firebase。 All the while, being loggedin to Google Api's thanks to Gapi's Javascript Library.一直以来,由于 Gapi 的 Javascript 库,登录到 Google Api。 You can use a gapi instance then to request resources and api's depending on your scope of course.您可以使用gapi实例然后根据您的范围请求资源和api。

 const contacts = await gapi.client.request({
        'path': 'https://people.googleapis.com/v1/people/me/connections?personFields=email_addresses,names&pageToken=CAAQwo2YuIUuGgYKAghkEAI&pageSize=2000',

      })

No CORS issues, no fuss.没有 CORS 问题,没有大惊小怪。 Just posting incase it helps someone else save some time.只是张贴以防它帮助其他人节省一些时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM