简体   繁体   中英

No 'Access-Control-Allow-Origin' header in Angular 6

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.

在此处输入图片说明

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM