1

I serve a angular2 webapp from mysite.com

My webapp is making calls from the browser to a nodejs backend.

For the moment I use mysite.com/api/ to call the api.

For system architecture reasons, I wish to call the api a different way, by using a subdomain:

api.mysite.com/

How can I get rid of the cross-origin issue?

Vincent Teyssier
  • 2,146
  • 5
  • 25
  • 62
  • Configure `api.mysite.com` to send the `Access-Control-Allow-Origin` response header and any other `Access-Control-*` response headers that might be needed in your scenario. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – sideshowbarker Mar 14 '17 at 16:24
  • this only works for images or other static resources not for xhr requests. And we are talking about client side, not server side cors issues – Vincent Teyssier Mar 14 '17 at 16:26
  • If don’t have access to configure anything on `api.mysite.com` then you can’t “get rid of the cross-origin issue” without using a proxy http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource/42744707#42744707. – sideshowbarker Mar 14 '17 at 16:39
  • But if you do have access to configure the web server at `api.mysite.com` then you can configure it to make it work with cross-origin XHR requests. At a minimum, you just need to configure it to send the `Access-Control-Allow-Origin` response header in the response. If it does, and your XHR request is a simple request that doesn’t trigger a preflight then that’s all you’d need to make it do. – sideshowbarker Mar 14 '17 at 16:39
  • Files are served by google cloud cdn on cloud storage buckets. I can set meta data so it should be fine. But I'm not sure my requests are only simple get requests. Will try tomorrow morning – Vincent Teyssier Mar 14 '17 at 16:42

1 Answers1

2

use JsonP take a look here : Jsonp:

 import { JsonP } from '@angular/http"; 
 @Injectable()
 export class dataService{
      constructor(jsonp:Jsonp) {

      }

      getData(){
        let url = 'http://api.mysite.com&c=JSONP_CALLBACK';
        jsonp.request(url, { method: 'Get' })
         .map( res => /...);
      }
    }
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37