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.
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);
}
`
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();
});
`
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
});
})();
}
}
Browser Warning: 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).
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…