Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can get correct response with Postman but body of the fetch response is empty

I send post request to my API that contains userName and password in the body. When I do that with Postman I can get a response which has a body contains a token.

enter image description here

But when I send the same request with fetch in fronted I get a responce with an empty body.

enter image description here

My feth is here:

async function login(){
    await fetch('/auth/login',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(
            {
                'userName' : userName,
                'password' : password,
            }
        )
    }
).then(
    res => {
        console.log(res)
        localStorage.setItem('Authorization',JSON.stringify(res))
    }
).catch(
    err => {
        console.log("Erorororor: " + JSON.stringify(err))
    }
)
}

What is the problem?

like image 717
I2mNew Avatar asked Jan 21 '26 16:01

I2mNew


2 Answers

I changed my code to

.then(res => return res.text()).then(data => console.log(data)).catch(...)
    

and now I can get the result which I want.

like image 170
I2mNew Avatar answered Jan 24 '26 06:01

I2mNew


TLDR Solution

It's caused by some header settings from the server side (For example, setting Access-Control-Allow-Origin: * twice will likely cause this issue). By tuning the headers you can fix it.

Details

I met the same issue. It's NOT caused by javascript code as the browser itself doesn't get body either, but headers and cookies are got.

enter image description here enter image description here enter image description here

By expanding the timing tab you can see a warning showing the request is not finished!

enter image description here

But the postman can get the body:

enter image description here

When

The same code works in the past. It came out recently. I'm not sure what's changed as there are many things changed, for example, the browser version, the nodejs version upgraded, etc.

Fixed

By tunning the headers in the server side fixed the problem.

enter image description here

like image 24
Jeff Tian Avatar answered Jan 24 '26 07:01

Jeff Tian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!