我正在尝试将我的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).
谢谢。
发布于 2019-02-20 04:27:33
在开发环境(本地主机)中,你可以很容易地做到这一点,而不需要遵循任何这些硬steps.You可以简单地下载https://addons.mozilla.org/firefox/addon/cors-everywhere/如果你正在使用火狐,我认为肯定有一个扩展为chrome also.After下载它会来到火狐菜单栏,然后你可以点击它来激活它,这就是你现在可以访问的所有apis,因为它自动发送与所有requests.For生产环境的头你必须从你的服务器配置它添加访问控制-允许-起源到*(所有)
发布于 2018-05-09 00:08:14
允许您从angular JS点击的服务器端,在这种情况下,您需要允许http://localhost:8888/
,因为那是您的服务器端URL,angular在http://localhost:4200
上运行。请检查Http。然后它就能工作了
https://stackoverflow.com/questions/50237881
复制相似问题