Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

No body on a GET request using fetch API?

I am sending (rather rying to) send a GET request to my server using the native JavaScript fetch API with an HTML client. On postman I can do this, no problems, what is wrong?

Here is the error:

Unhandled Promise Rejection: TypeError: Request has method 'GET' and cannot have a body

Again, I need to make a GET request, not a post request… Postman does allow this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the code:

fetch('http://www.localhost:3000/get-data', {
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        a: 1,
        story: document.getElementsByTagName("input")[0].value,
    })
});

PD: I using Safari, bur Chrome, although marking a different looking error that conveys the same message, still does not work.

>Solution :

You can not use body with GET request. If you want to pass params with GET request then the official way to work with query parameters is just to add them onto the URL. This is an example:

var url = new URL("http://www.localhost:3000/get-data"),
    params = {
        a: 1,
        story: document.getElementsByTagName("input")[0].value,
    }
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading