3

I'm leaning Angular, trying to use HTTP get to a json file on localhost url http://api.test/work.but I get the error bellow:

Failed to load http://api.test/work: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

by the way I use laravel to generate json

Saleem Hakeem
  • 33
  • 1
  • 3

3 Answers3

0

This means that, http://api.test/work.but does not allow cross origin request. If this link is hosted by you, you will have to allow cross origin request. In your response headers, you will have to send: Access-Control-Allow-Origin: *

This means, any body request to your server.

If you want to allow access to specific domains, you can specify them.

Read more abouut CORS here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

ashfaq.p
  • 5,379
  • 21
  • 35
  • How to specify this thing . My code in angular : import {Injectable} from '@angular/core'; import {Http, Response} from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WorkService { constructor(private http: Http) { } private url: string = '//api.test/work'; getWork() { return this.http.get(this.url).map((response: Response) => response.json()); } } – Saleem Hakeem Apr 23 '18 at 08:34
  • This has got nothing to do with angular. This needs to be added from your api server. The server should allow you CORS. – ashfaq.p Apr 23 '18 at 08:39
  • I got it now I was think the problem from angular code thanks allot – Saleem Hakeem Apr 23 '18 at 08:46
0

I was getting the same error; "Failed to load http://web-api_link: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.". I already had CORS installed on my chrome browser. It was on. I clicked on it and checked for "Enable cross-origin resource sharing". I disabled it, and enabled it again. It worked for me!

vsg
  • 175
  • 2
  • 11
-1

private callServiceGet(url: string, wC?: boolean): Promise<any> {
    return this.http.get<any>(url, { observe: 'response', withCredentials: wC })
      .catch(err => [ err ])
      .map(data => ({ status: data.status, data: data.body }))
      .toPromise();
  }

with wC you have credentials to allow localhost too. It's simply a boolean, so set it to true if you want a complete access.

for example you could use it like this:

getJSON(): Promise<any> {
    return this.callServiceGet(`http://api.test/work`, true);
  }
Luca Taccagni
  • 1,059
  • 6
  • 23