Search code examples
c#reactjsfetch-apihttp-status-code-401

Error 401 when trying fetch data using custom API with POST method


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);
        });
    };

Solution

  • Is CORS error. Try this in your API:

    services.AddCors(options => {
       options.AddPolicy("AllowAll",
       builder => builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader());
    });
    

    And then:

    app.UseCors("AllowAll");
    

    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.