【发布时间】:2020-01-17 09:48:58
【问题描述】:
我在 Google App Engine 上部署了 2 个应用程序;
A 是一个 Angular 8 应用程序。
B 是一个 Node.js express 应用程序。
每当我尝试在后端调用 API 时,都会收到此错误:
Access to XMLHttpRequest at '"APPLICATION B"/getGroups?userKey=' from origin 'APPLICATION A' 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.
我确保在 APPLICATION B 的谷歌应用引擎凭据中启用 APPLICATION A url 作为授权 Javascript 源和授权重定向 URI。 在 localhost 中一切正常。
我在 App.js 上的尝试:
尝试 1
app.use(function (req, res, next) {
res.header(“Access-Control-Allow-Origin”, “*”);
res.header(“Access-Control-Allow-Methods”, “GET,HEAD,OPTIONS,POST,PUT”);
res.header(“Access-Control-Allow-Headers”, “Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization”);
next();
});
尝试 2
var cors = require('cors')
app.use(cors())
尝试 3
var cors = require('cors')
var corsOptions = {
origin: 'APPLICATION A',
}
app.use(cors(corsOptions ));
app.options('*', cors());
这是我在 Angular 8 应用程序 A 中执行的 GET
getGroupsRequest(id): Observable<any> {
const url = "APPLICATION B"
return this.http.get(url + id);
}
如果我使用 CORS 插件或打开谷歌浏览器“--disable-web-security”,它就可以工作。
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\Users\510919\ChromeDev" --disable-web-security --auto-open-devtools-for-tabs
【问题讨论】:
标签: node.js angular google-app-engine cors