Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No 'Access-Control-Allow-Origin' header in Angular 2 app

For this project, I'm just learning and practicing Angular 2. I have no server-side and am making API requests to barchart ondemand api .

I'm wondering if it is possible to bypass the cors issue. I'm still fairly new to all this, so baby-step instructions are really appreciated! I'm using http://localhost:8080.

Error message: (api key commented out)

XMLHttpRequest cannot load http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&symbol=GOOG&type=daily&startDate=20150311000000. 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:8080' is therefore not allowed access.

StockInformationService:

import {Injectable} from 'angular2/core'; import {Http, Headers} from 'angular2/http'; import {Observable} from 'rxjs/Rx';  @Injectable() export class StockInformationService {     private apiRoot = "http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&";      constructor (private _http: Http) {}      getData(symbol: string): Observable<any> {         // Tried adding headers with no luck         const headers = new Headers();         headers.append('Access-Control-Allow-Headers', 'Content-Type');         headers.append('Access-Control-Allow-Methods', 'GET');         headers.append('Access-Control-Allow-Origin', '*');          return this._http.get(this.apiRoot + "symbol=" + symbol + "&type=daily&startDate=20150311000000", {headers: headers})             .map(response => response.json());     } } 

App Component:

import {Component} from "angular2/core"; import {VolumeComponent} from '../../components/volume/volume'; import {StockInformationService} from '../../core/stock-information.service';  @Component({     selector: 'app-shell',     template: require('./app-shell.html'),     directives: [VolumeComponent],     providers: [StockInformationService] }) export class AppShell {     constructor(private _stockInformationService: StockInformationService) {}      // In my template, on button click, make api request     requestData(symbol: string) {         this._stockInformationService.getData(symbol)             .subscribe(                 data => {                     console.log(data)                 },                 error => console.log("Error: " + error)             )}     }  } 

In my console, the requestData Error: Error: [object Object]

like image 316
philip yoo Avatar asked Mar 15 '16 04:03

philip yoo


People also ask

How do you fix CORS header access-control-allow-Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

How do you solve CORS issue in angular 8?

CORS error due to browser's same origin policy. To get around this, you need to tell your browser to enable your client and your server to share resources while being of different origins. In other words, you need to enable cross-origin resource sharing or CORS in your application.

What is CORS policy no access-control-allow-origin?

The access-control-allow-origin plugin essentially turns off the browser's same-origin policy. For every request, it will add the Access-Control-Allow-Origin: * header to the response. It tricks the browser, and overrides the CORS header that the server has in place with the open wildcard value.


2 Answers

This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code

// Add headers app.use(function (req, res, next) {      // Website you wish to allow to connect     res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');      // Request methods you wish to allow     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');      // Request headers you wish to allow     res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');      // Set to true if you need the website to include cookies in the requests sent     // to the API (e.g. in case you use sessions)     res.setHeader('Access-Control-Allow-Credentials', true);      // Pass to next layer of middleware     next(); }); 

that code was an answer of @jvandemo to a very similar question.

like image 78
Pablo Ezequiel Inchausti Avatar answered Oct 10 '22 19:10

Pablo Ezequiel Inchausti


You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.

Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers. check that you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*" 
like image 20
Nitheesh K P Avatar answered Oct 10 '22 17:10

Nitheesh K P