How to Send Query Params in GET and POST in JavaScript

Ferenc Almasi β€’ 2022 July 21 β€’ πŸ“– 4 min read

To send query parameters in a POST request in JavaScript, we need to pass a body property to the configuration object of the Fetch API that matches the data type of the "Content-Type" header.

(async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({
            title: 'This will be the title',
            body: 'Setting the body property',
            userId: 1,
        }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8'
        },
    })

    const data = await response.json()

    console.log(data)
})()
Copied to clipboard!

The body will always need to match the "Content-type" header.

Notice that you will also need to set the methodΒ property to "POST". Make sure you wrap your object into JSON.stringify in order to pass a proper JSON payload.

We can wrap the entire call into an async IIFE in order to use await. We can also create a helper function for later use that expects a URL and an object for the query parameters:

const post = async (url, params) => {
    const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(params),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
        }
    })

    const data = await response.json()

    return data
}

// Then use it like so with async/await:
(async () => {
    const data = await post('https://jsonplaceholder.typicode.com/posts', {
        title: 'This will be the title',
        body: 'Setting the body property',
        userId: 1
    })

    console.log(data)
})()

// Or using then:
post('https://jsonplaceholder.typicode.com/posts', {
    title: 'This will be the title',
    body: 'Setting the body property',
    userId: 1,
}).then(data => console.log(data))
Copied to clipboard!

Then we can call it either using async/await, or using a then callback.


How to Send Query Parameters in GET

To send query parameters in a GET request in JavaScript,Β we can pass a list of search query parameters using the URLSearchParams API.

(async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/comments?' + new URLSearchParams({
        postId: 1
    }))

    const data = await response.json()

    console.log(data)
})()
Copied to clipboard!

This will convert the object into a string with key-value pairs. Eg, the above example would become "postId=1". Notice that here, you don't need to pass a method property for the Fetch API, as it uses GET by default. We can also use a helper function for this one too to make the call reusable:

const get = async (url, params) => {
    const response = await fetch(url + '?' + new URLSearchParams(params))
    const data = await response.json()

    return data
}

// Call it with async:
(async () => {
    const data = await get('https://jsonplaceholder.typicode.com/comments', {
        postId: 1,
    })

    console.log(data)
})()

// Calling it with then:
get('https://jsonplaceholder.typicode.com/comments', {
    postId: 1,
}).then(data => console.log(data))
Copied to clipboard!
Remove ads
Remove ads

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
πŸŽ‰ Thank you for subscribing to our newsletter. x