Angular CORS 请求被阻止 [英] Angular CORS request blocked
问题描述
我正在尝试将我的 Angular 应用程序与 Express 上的简单 REST 服务器连接起来.服务器只发送 json
数据来回复请求.为了添加 CORS
支持,我使用了 npm 中的 cors
模块.在 Angular 应用程序上,我按照以下问题的说明添加了 HttpHeaders
:Angular CORS 请求被阻止.
I am trying to connect my Angular app with a simple REST server on express. The server only sends json
data in reply to request. To add CORS
support, I used the cors
module from npm. On the Angular app, I added HttpHeaders
following the instructions from this question: Angular CORS request blocked.
这是我设置 cors 选项的 express 代码:`
Here is my code in express where I set up the cors Options: `
// async CORS setup delegation
function corsOptsDelegator(req, cb) {
let opts = {},
origin = req.header('Origin');
if(imports.allowedOrigins.indexOf(origin) === 1) opts.origin = true;
else opts.origin = false;
opts.optionsSuccessStatus = 200;
opts.methods = ['POST', 'GET']; // allowed methods
opts.credentials = true; // for passing/setting cookie
opts.allowedHeaders = ['Content-Type', 'Accept', 'Access-Control-Allow-Origin']; // restrict headers
opts.exposedHeaders = ['Accept', 'Content-Type']; // for exposing custom headers to clients; use for hash
cb(null, opts);
}
`
这是我将它添加到全局 get
处理程序的方法:
Here's how I added it to the global get
handler:
`
app.get('/', cors(corsOptsDelegator), (res, req, nxt) => {
// only for adding cors on all requests
nxt();
});
`
我是这样设置 Angular 服务的:
Here's how I set up the Angular service:
`
export class ContentGetterService {
private root: string;
private corsHeaders: HttpHeaders;
//private contents: string;
constructor(private http: HttpClient) {
this.root = 'http://localhost:8888';
this.corsHeaders = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:4200'
});
//this.contents = '';
}
getContent(subs: Array<string>): Observable<IContent> {
return (() => {
return this.http.get<IContent>( (() => {
let r = this.root;
subs.forEach((s, i, a) => {
if(i === a.length-1) {
r += s;
}
else {
if(s !== '/') {
r += s;
}
}
});
return r;
})(), {
headers: this.corsHeaders
});
})();
}
}
浏览器警告:跨域请求被阻止:同源策略不允许读取位于 http://localhost:8888/的远程资源.(原因:缺少 CORS 标头Access-Control-Allow-Origin").
谢谢.
推荐答案
如果你使用 angular-cli,你可以使用代理:
In case you are using angular-cli, you can use a proxy:
proxy.conf.json:
{
"/api": {
"target": "http://localhost:8888",
"secure": false
}
}
将所有带有 /api
前缀的请求重定向到 localhost:8888 而没有任何 cors 问题.
Will redirect all requests with /api
prefix to localhost:8888 without any cors issue.
官方文档:https://angular.io/guide/build#proxying-to-a-backend-server
这篇关于Angular CORS 请求被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!