0
votes

I'm creating a little app using NodeJs and Ionic v3 and I'm stuck with CORS error:

Failed to load http://localhost:3000/crm/getAllClients: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

I've set CORS in nodeJs like this:

app.use(cors());

To make HTTP request with Ionic I'm using :

import {HttpClient, HttpHeaders} from "@angular/common/http";

Here's my code in my Ionic service:

 initHeaders() {
    let headers = new HttpHeaders()
      .set('Access-Control-Allow-Origin', "*")
      .set("Content-Type", "application/json")
      .set("Access-Control-Expose-Headers", "Content-Length");

    return headers;
  }

  getAllClients () {
    return this.http.get(this.domain + 'crm/getAllClients', {headers: this.initHeaders()});
  }

Here are the headers with no header set:

enter image description here

Am I doing something wrong ?

2
Can you console.log headers before returning them? - Roberto Zvjerković

2 Answers

1
votes

I had a similar issue in the past. As far as I understand you are not doing anything wrong, your three headers are inside "Access-Control-Request-Headers" (in your screenshot under "Request Headers". The browser joins all your CORS headers and puts them in "Access-Control-Request-Headers".

My bet is that there is a problem with the cors configuration in node. I would try something like this in you express app:

app.use(function (req, res, next) {
res.header("Access-Control-Allow-Headers", "Access-Control-Expose-Headers, Content-Type, Accept");
next();
});

instead of using

app.use(cors())

Or check that you are writing app.use(cors()) before adding the routes, so that the routes are using cors.

0
votes

My problem was that I called cors Middleware after I've set routes on my app.js in node !

// set it before routes !
app.use(cors());

app.use('/', index);
app.use('/crm', crm);