I have a react app running on localhost:3000 and I try to consume calling REST API by java ee backend rest server, running on localhost:8080. I have enabled CORS on header.
I tried to make a form submit post request on my component.
fetchApi = () => {
const url = 'http://localhost:8080/test/api/rest/Service/checkCode';
var myHeaders = new Headers();
myHeaders.append('Access-Control-Allow-Origin', '*');
myHeaders.append('Access-Control-Allow-Headers', 'origin, content-type, accept, authorization');
myHeaders.append('Access-Control-Allow-Credentials', 'true');
myHeaders.append('Access-Control-Allow-Methods', ' GET, POST, PUT, DELETE, OPTIONS, HEAD');
myHeaders.append('Content-Type', 'application/json');
var myInit = {
method: 'POST',
headers: myHeaders,
mode: 'cors',
cache: 'default',
body: JSON.stringify({
code: '15465',
name: 'Jack',
})
};
fetch(url, myInit)
.then(function(response) {
if (response.ok) {
return response.json();
}
else{
throw new Error('Network response was not ok');
}
}).then(function(data){
console.log(data);
this.setState({items: data});
}).catch(function(error){
console.log('There has been a problem with your fetch operation: ' + error.message);
})
};
I have errors in line:
fetch(url, myInit):
OPTIONS http://localhost:8080/test/api/rest/Service/checkCode 500 (Erreur Interne de Servlet)
And CORS Error:
Fetch API cannot load http://localhost:8080/test/api/rest/Service/checkCode. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'ttp://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
mode: 'no-cors'and disable CORS. - bennygenelmyHeaders.append('Access-Control-Allow…')stuff from your request code. Those are all response headers for servers to send back. Adding them to requests in your client code is just going to break things. - sideshowbarker