vendredi 10 mars 2017

Error in Access-Control-Allow-Origin when Angular request to Rails

I'm using Angular 2 to make an API(rails) request. When I make the http request through angular, I get the following error: XMLHttpRequest cannot load https://api-url. 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:4200' is therefore not allowed access. The response had HTTP status code 404. However, if I try to make a request through Postman or the browser itself, I don't get any error. The data is displayed normally angular code:

makeRequest() {
  let user = {"user": "user", "password": "password"};
  let headers: Headers = new Headers();
  headers.append('Authorization', 'Basic ' + btoa(user.user + ':'+user.password));
  headers.append('Content-Type', 'application/vn.api+json')
  let this.http.get(api-url, {headers: headers}).map(res => res.json()).subscribe(data => {
  this.data = data;
  })
 }

In my rails server i using the gem 'jsonapi-resources'to open AP. In my api controller, i have this code to authenticate and set headers to requests:

module Api
  class ApiController < JSONAPI::ResourceController
    prepend_before_action :set_headers, :authenticate

    def context
      { current_station: @user }
    end

    private

    def authenticate
      authenticate_or_request_with_http_basic do |token, _|
      @user = User.where(api_key: token).first
      end
    end

    def set_headers
      response.headers["Access-Control-Allow-Origin"] = "*"
    end
  end
end

When i make request in browser or using postaman, the header appears normally, but in Angular i have the error.

Aucun commentaire:

Enregistrer un commentaire