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
suppor
In case you are using angular-cli, you can use a proxy:
proxy.conf.json:
{
"/api": {
"target": "http://localhost:8888",
"secure": false
}
}
Will redirect all requests with /api
prefix to localhost:8888 without any cors issue.
Offical docs: https://angular.io/guide/build#proxying-to-a-backend-server
Firstly, the problem on the client was due to the behavior of Firefox opting in to handle pre-flight CORS. Instead of using GET
method,OPTIONS
method was used. As it is evident from my code, I do not have any handler for handling OPTIONS
. After some googling, I came across this post on github: Express CORS middleware. Using this and making the following modifications to my client request headers, I was able to properly get it up and running. Here's the code:
CORS Middleware:
function myCors(req, res, nxt) {
res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
res.header('Access-Control-Allow-Methods', 'GET,PUT,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Content-Type, Accept, Accept-Language, Origin, User-Agent');
if(req.method === 'OPTIONS') {
res.sendStatus(204);
}
else {
nxt();
}
}`
Mounting it to the app instance:
app.use(myCors);
On the Angular client side service:
this.corsHeaders = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:8888/'
});
// ... adding it to the request
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
});
})();
}
Thanks everyone for their time and efforts.
Allow Server side that you hit from angular JS, in that case you need to allow http://localhost:8888/
because that is your server side URL, angular run on http://localhost:4200
. please check the Http. then it work
In development environment(localhost),you can do it easily without following any of these hard steps.You can simply download https://addons.mozilla.org/firefox/addon/cors-everywhere/ if you are using firefox and i think there must be an extension for chrome also.After downloading it will come to the firefox menubar and then you can click it to activate it,thats all you can now access to all apis as it automatically sends header with all requests.For production environment you have to configure it from your server by adding access-control-allow-origin to * (all)
Use this code and manage yourself according to your structure.
app.use(
cors({
origin: http://localhost:4200,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
allowedHeaders: [
'Content-Type',
'Authorization',
'Origin',
'x-access-token',
'XSRF-TOKEN'
],
preflightContinue: false
})
);
app.get('/', (res, req, nxt) => {
// only for adding cors on all requests
nxt();
});
On Angular Side
constructor(private http: HttpClient) {
this.root = 'http://localhost:8888'; //remove
this.corsHeaders = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '/' . // edit
});
//this.contents = '';
}
and use <base>
index.html