-2

I want to have an API with an external server. When I do with postman program, it's easy to answer. But when I do this in Angular code, it response following error:

Access to XMLHttpRequest at 'https://api.smartship.io/ship/rates' from origin 'http://127.0.0.1:4200' 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.

MY service:

let api_url = this.api_url_flagship + '/con';
let headers = new HttpHeaders({
  'x-smartship-token': this.token_flagship,
  'Content-Type': 'application/json'
});

const httpOptions = {
    headers
};


return this.httpClient.post(api_url, data, httpOptions)    
  .map(
    (response: Response) => {
      const data = response.json();
      return data;
    }
  )
  .catch(
    (error: Response) => {
    let rr = error.json();
    return Observable.throw(rr);
  }
);
Ali
  • 2,541
  • 2
  • 17
  • 31
  • 4
    Possible duplicate of [AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource](https://stackoverflow.com/questions/29547003/angularjs-no-access-control-allow-origin-header-is-present-on-the-requested-r) – Liam Jul 15 '19 at 11:07
  • Same as everyone else with CORS issues - you either need a proxy, or to configure the server correctly for your client. – jonrsharpe Jul 15 '19 at 11:12
  • @jonrsharpe Should I contact the server to accept the domain – Ali Jul 15 '19 at 11:28

2 Answers2

1

To ensure that this is a backend issue, use this plugin https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Enable it, and then send the request. It should work in most cases.

If it works, then we can conclude that it's and backend issue.

If you are using node,then you can allow localhost in app.js (I use the CORS library for the same). If not, then you can search this around for the language you are using ,or raise a question under that language domain.

ishan srivastava
  • 363
  • 1
  • 3
  • 10
  • Thanks for your answer. I did that, but I saw that error again. Is the problem from my angular code? – Ali Jul 15 '19 at 11:49
0

that problem comes from the APIs server side is not accepting the requests comes from 127.0.0.1 so try to use to access to your app from

 http://localhost:4200 

if it does not work try to change the host file data record to that

 127.0.0.0 myapp.com 

then use myapp.com as domain name

http://myapp.com:4200 
Mohamed Maher
  • 163
  • 1
  • 10