Reputation: 31546
I have written a redux application which I am running locally using webpack-dev-server. (port 8080). I am trying to connect to a web service which is running locally at port 9000.
My code to connect to the web service is as follows
return fetch(`http://localhost:9000/movies/${dimensionName.toLowerCase()}list`)
.then(response => response.json())
.then(json =>
dispatch(receivedDimensionAttributesSuccess(dimensionName, json))
)
.catch(error =>
dispatch(receivedDimensionAttributesError(dimensionName, error))
);
This receives an error
Fetch API cannot load http://localhost:9000/movies/yearlist. No 'Access-
Control-Allow-Origin' header is present on the requested resource. Origin
'http://localhost:8080' is therefore not allowed access. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the resource
with CORS disabled.
I googled for the problem and found this thread
Access Control Allow Origin header not present with fetch api call
but I don't like the solution which involved switching to a different library/middleware altogether.
How can I solve the problem with the isomorphic fetch library.
Upvotes: 4
Views: 17216
Reputation: 31
you can simply add {mode:'no-cors',}
to disable the No 'Access-
Control-Allow-Origin' header. For more information you can refer the following url :
https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api
return fetch(`http://localhost:9000/movies/${dimensionName.toLowerCase()}list`**,{mode:'no-cors'**,})
.then(response => response.json())
Upvotes: 2
Reputation: 39
you must use
let header = new Headers({
'Access-Control-Allow-Origin':'*',
'Content-Type': 'multipart/form-data'
});
instead of
let defaultOptions = {
url:'',
method:'POST',
mode: 'cors',
headers:{
'Access-Control-Allow-Origin':'*'
},
body:null,
};
to enable cors
Upvotes: 3
Reputation: 5020
Access-Control-Allow-Origin
is something you can control at client side. It is a security restriction for browsers that requires to be negotiated with the server.
A server can retrieve data from any end-point, but for browser apps this is different. For security reasons you are only allowed to load data via XHR from the same server you have loaded the web page. If you need to load data from a different server (say an external API) the browser requires that server responds indicating you are allowed.
See description in the "Cross Domain Request" section on http://www.acuriousanimal.com/2011/01/27/working-with-the-javascript-xmlhttprequest-object.html
Upvotes: 1
Reputation: 11
You can read this https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
fetch(url[, init])
set the init param to allow cross-domain request
try
Upvotes: -2