I'm trying to send an http request using fetch to my backend but it's returning this error even though I'm sending an application/json header, the content that needs to reach the api is a json
front-end code
let user_ = 'teste';
let email_ = 'teste@email.com';
let pass_ = 'teste';
let button_submit = document.getElementById('mySubmit_signup');
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Credentials', 'true');
button_submit.addEventListener('click', async function(){
try {
await fetch('http://localhost:8080/users', {
mode: 'cors',
method: 'POST',
body: JSON.stringify({
name: user_,
email: email_,
password: pass_
}),
})
.then(
response => response.json()
)
.then(
data => console.log(data)
)
} catch (error) {
console.log(error);
}
});
ATT:
i add header but i receive "Access to fetch at 'http://localhost:8080/users' from origin 'http://localhost:7777' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
try {
await fetch('http://localhost:8080/users', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({
name: "user_",
email: "mail_@email.com",
password: "pass_"
}),
})
.then(
response => response.json()
)
.then(
data => console.log(data)
)
} catch (error) {
console.log(error);
}
};
req();