krhitesh
krhitesh

Reputation: 787

CORS: How to set 'Access-Control-Allowed-Origin' request header

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:3000' is therefore not allowed access. The response had HTTP status code 522. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 522. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

How to add a request header to json ?

var options = {
        body: info,
        type: 'json'
    }

And then `

doGetCall(url, options = {}) {
let callOptions = {
  method: 'GET'
}
callOptions.headers = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': 'http://localhost:3000'
}

return this.doCall(url, callOptions);

}

finally

doCall(url, options) {
if (!options.noauth) {
  options.headers = options.headers || {};
  options.headers.Authorization = 'Bearer ' + Account.token;
}
return fetch(url, options).then(response => response.json());

}

This does not work out. The request header has:

access-control-request-headers:access-control-allow-origin,authorization,content-type

But no Access-Control-Allowed-Origin header. How add that header?

Upvotes: 0

Views: 6120

Answers (1)

mylnz
mylnz

Reputation: 424

Check this answer: How does CORS works

For overview:

  1. Enable CORS options to add "Access-Control-Allow-Origin": "*" header to your response. Dont add authonticater to Options resources.

  2. For best practice, if you add these headers to your response, you don't need to override the browser settings.

"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true

  1. check your request url/endpoint to be sure is ok.

Upvotes: 1

Related Questions