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
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 index.html