0

I am getting Access-Control-Allow-Origin error.

Access to XMLHttpRequest at 'https://localhost:44301/api/XXXX/GetAllXXXX' from origin 'https://localhost:44322' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

enter image description here

And below is my header which i have passing to api call.

getAllItems<T>(): Observable<T> {
const options = { headers: this.getRequestHeaders() };
return this.http.get<T>(this.getAllItemUrl, options);

}

protected getRequestHeaders(): HttpHeaders {
let headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Accept': `application/json, text/plain, */*`,
  'App-Version': '1',
});
return headers;

}

Am i missing anything to connect my API's here?

tt0206
  • 747
  • 3
  • 9
  • 24
  • You need to ensure your backend sends the `Access-Control-Allow-Origin` header. There should be plenty of resources surrounding this online if you search for CORS – user184994 Nov 06 '18 at 18:23
  • Check my answer here, https://stackoverflow.com/questions/53167985/angular-and-php-project-access-control-allow-origin-header-contains-multiple-v/53168191#53168191 This is a better option than using CORS – inthevortex Nov 06 '18 at 22:41

1 Answers1

1

You need to add CORS to your backend service. If its an express based service you can have something like this

const express = require('express');
const app = express();


var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

app.use(allowCrossDomain);
Rakesh M
  • 41
  • 1
  • 7