My friend and I are working on a college project (Reservations related web app) using React and C#.
Basically he made an API where users must input their data and after submitting, their data should be successfully sent to database. In my case, I get error 401 after submitting the data although I checked my JWT token and it’s the same one I got after logging in. I tried this using Postman and it worked. I am curious why it won’t work on my browser with the code submitted down below.
Thank everyone who can help. I am sorry if someone would find this question stupid but I’m relatively new to web development and I don’t know how to fix this issue.
const handleSubmit = () => {
const data = {
userEmail: Cookies.get('email'),
userPhoneNumber: phone,
town: city,
country: country,
street: street,
houseNumber: houseNumber,
postalCode: postalCode,
businessName: jobName,
businessIdentificationNumber: 0,
businessType: 0,
businessActivities: [
{
nameOfActivity: "string",
descriptionOfActivity: "string",
price: 0
}
],
workingDays: Object.values(workingDays),
startingHours: Object.values(workingHours).map(hours => hours.open),
endingHours: Object.values(workingHours).map(hours => hours.close)
};
fetch('http://localhost:8000/api/business/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + jwt
},
body: JSON.stringify(data),
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
2
Answers
It may be a CORS error. The 401 response code is sent by the Access-Control-Allow-Origin header when your backend isn’t configured with CORS. Verify if your API has CORS configured (usually it’s simple to configure).
Is CORS error. Try this in your API:
And then:
Allowing all origins may not be the best practice, but if it’s working, the issue may lie in the CORS configuration you’ve implemented.