I tried many things, it will only POST to the api when it has "mode: no-cors" and no headers.
I am now trying with mode: 'cors', because i've read that i shouldn't use 'no-cors' because of security reasons. BUT, i do have to remove the headers or else it won't POST the data.
Here's the code:
signUp: async(email, password)=> {
let values = {
firstname: "pruebaNombre",
lastname: "pruebaApellido",
email: email,
password: password
}
const config = {
method: 'POST',
mode: 'cors',
// headers: {
// 'Access-Control-Allow-Origin':'*',
// 'Content-Type': 'application/json'
// },
body: JSON.stringify(values),
}
const response = await fetch('http://localhost/rest-api-authentication-example/API/create_user.php', config);
const data = await response.json();
console.log(data);
}
The console.log(data) should be a json with a message saying "user was created", but i get these errors:
Access to fetch at 'http://localhost/rest-api-authentication-example/API/create_user.php' from origin 'http://localhost:19006' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost/rest-api-authentication-example/' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Failed to load resource: net::ERR_FAILED
Uncaught (in promise) TypeError: Failed to fetch
The data does get posted on my server, but i can't get a the response from the fetch.
EDITED.- These are my headers on my server side:
header("Access-Control-Allow-Origin: http://localhost/rest-api-authentication-example/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");