Search code examples
javascriptspring-boothttpcorsfetch

Content type 'text/plain;charset=UTF-8' not supported in fetch js ti api spring boot


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_ = '[email protected]';
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: "[email protected]",
                password: "pass_"
            }),
        })
        .then(
            response => response.json()
        )
        .then(
            data => console.log(data)
        )
    } catch (error) {
        console.log(error);
    }
};

req();

Solution

  • You are passing a string to body. This means fetch will automatically add a Content-Type request header saying that you are sending plain text.

    Your server side code is expecting JSON and is rejecting your so-called plain text with an error.

    You need to explicitly add the correct header to say that you are sending JSON.

            headers: {
                'Content-Type': 'application/json',
            },
    

    Aside Do not add 'Access-Control-Allow-Origin': '*', to your request headers. This is a response header and has no business being on the request. Adding it will create additional problems.


    Adding an application/json content type to the request will make it preflighted.

    You quoted an error mentioning a preflight request. The error state may have been caused by your incorrect extra header (see the aside above) or it might be that your server isn’t set up to support any preflight request.

    If the latter then you need to adjust the server-side code to response to the preflight request (which is OPTIONS rather than POST) to give permission to the browser to make the POST request you want to make.