How to Send Query Params in GET and POST in 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:
(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)
})()
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:
// 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))
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)
})()
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:
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))
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:
- npm i axios # Using NPM
- yarn add axios # Using Yarn
- pnpm add axios # Using PNPM
- bower install axious # Using Bower
Once Axios is installed, we need to import it, and then we can create a GET
request with query params using the following code:
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)
})()
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:
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)
})()
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 thebody
when using aPOST
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.
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: