How to Send Query Params in GET and POST in JavaScript

Ferenc Almasi β€’ Last updated 2023 November 11 β€’ Read time 6 min read
  • twitter
  • facebook
JavaScript

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:

Copied to clipboard! Playground
(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)
})()
How to send parameters in POST request

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 to pass a proper JSON payload.

We can wrap the entire call into an async IIFE to use await. Alternatively, we can create a helper function for later use that expects a URL and an object for the query parameters. Then we can call it either using async/await, or using a then callback:

Copied to clipboard! Playground
// Create a helper function called `post`
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
}

// 1️⃣ 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)
})()

// 2️⃣ 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))
Copy the post function to your code to use it

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.

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

    const data = await response.json()

    console.log(data)
})()
Setting query params in GET

This will convert the object into a string with key-value pairs. For example, 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 to make the call reusable:

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

    return data
}

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

    console.log(data)
})()

// 2️⃣ Calling it with then:
get('https://jsonplaceholder.typicode.com/comments', {
    postId: 1,
}).then(data => console.log(data))
Copy the get function into your code to use it

How to Send Query Parameters with Axios

While sending query parameters in vanilla JavaScript is possible with a few lines of code, some may prefer the simplicity of Axios, a library for handling HTTP requests with wrapper functions. To use Axios, we first need to install it with a package manager:

Copied to clipboard!
- npm i axios          # Using NPM
- yarn add axios       # Using Yarn
- pnpm add axios       # Using PNPM
- bower install axious # Using Bower
Install Axios with one of the above commands

Once Axios is installed, we need to import it, and then we can create a GET request with query params using the following code:

Copied to clipboard! Playground
import axios from 'axios'

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

    console.log(data)
})()
GET request in Axios

If you need to use a POST request with parameters, this can be achieved by using axios.post with a second parameter containing the parameters. Using the previous POST example, this would translate to the following in Axios:

Copied to clipboard! Playground
import axios from 'axios'

(async () => {
    const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
        title: 'This will be the title',
        body: 'Setting the body property',
        userId: 1,
    })

    console.log(response)
})()
POST request in Axios
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Best Practices for Using Query Params

When it comes to using query parameters, there are a number of things we need to keep in mind. Here are some best practices you should follow when working with query parameters:

  • Don't send sensitive information in GET: Only use query parameters for non-sensitive data. For sensitive information, use a POST request.
  • Keep below the limit: Don't pollute the URL with too many query parameters. There is a maximum limit browsers can handle. After reaching the limit, the URL will be stripped, which can result in unexpected behavior. This limit varies for each browser. Keeping the length of the URL under 2000 characters is a good rule of thumb that will ensure your functionality works across virtually every device.
  • Provide content type: Always make sure the Content-type header matches the format of the body when using a POST request.

Summary

To summarize, use a GET request for simple communication with the server and when you don't need to handle sensitive data. Use GET to make URLs sharable. The presence of query parameters can ensure that users can save pages with different configurations, for example, with filters preset.

Use POST when you need to send either sensitive data or large amounts of data. Match the body with the Content-type header, and prefer using async/await for improved readability and less nesting.

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.