我正在尝试将我的 Angular 应用程序与 express 上的简单 REST 服务器连接起来。服务器只发送json
数据作为对请求的回复。为了添加 CORS
支持,我使用了 npm 中的 cors
模块。在 Angular 应用程序上,我按照以下问题的说明添加了 HttpHeaders
:Angular CORS request blocked .
这是我在 express 中设置 cors 选项的代码: `
// 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
处理程序的方式:
`
app.get('/', cors(corsOptsDelegator), (res, req, nxt) => {
// only for adding cors on all requests
nxt();
});
`
以下是我设置 Angular 服务的方式:
`
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 header “Access-Control-Allow-Origin”)。
谢谢。
最佳答案
如果您使用的是 angular-cli,则可以使用代理:
proxy.conf.json:
{
"/api": {
"target": "http://localhost:8888",
"secure": false
}
}
将所有带有 /api
前缀的请求重定向到 localhost:8888,没有任何 cors 问题。
官方文档:https://angular.io/guide/build#proxying-to-a-backend-server
关于Angular CORS 请求被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50237881/