我尝试了与其他线程不同的一些解决方案,并怀疑我在这里缺少一些小东西。
我有一个AngularJS 8应用程序,它在带有ExpressJS的Node 10上运行。尝试访问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
我的前端代码如下:
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',
})
});
}
我的服务器端代码:
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();
});
您可以看到,我尝试了几种不同的方法。不胜感激。
谢谢
答案 0 :(得分:0)
以另一种方式解决了该问题。使用Gapi库(javascript:https://github.com/google/google-api-javascript-client/blob/master/docs/reference.md)及其Auth,我能够登录,获取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;
使用该凭据登录到Firebase。一直以来,由于有Gapi的Javascript库,因此可以登录到Google Api。当然,您可以使用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',
})
没有CORS问题,没有大惊小怪。只是发布以防其他人节省时间。