我正在尝试将我的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
});
})();
}
}
浏览器警告:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8888/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
谢谢。
https://stackoverflow.com/questions/50237881
复制相似问题