iTranslated by AI
Why You Can't Send a Request Body with GET in JavaScript
Lessons Learned When Creating a GET API
- When information is required for a GET request, specify it using path parameters or query parameters.
- When information is required for a GET request, consider using methods other than GET.
I ended up creating a problematic API.
It was one that required data in a GET request. I tested it thoroughly with Postman. The response returned a 200, and it provided the data I was looking for.
The problem occurred when I tried to request this from JavaScript.
What Happened
I was using React as the framework. I planned to use SWR for the process of sending the API GET request. I looked through the official documentation to find out how to include data, but I couldn't find anything. I felt a slight sense of suspicion, but I didn't take it that seriously.
When I sent the request with the following code, it returned a 500 error.
import axios from 'axios'
import useSWR from 'swr'
const fetcher = ({ url, config }) => axios(url, config).then((res) => res.data)
export const fetchData = (id) => {
const config = {
method: 'get',
...,
data: JSON.stringify({ id: id })
}
const { data, error } = useSWR([`/data` args], fetcher)
return { raasId: data, raasIdError: error }
}
The request itself seems to be firing, but there is no trace of data being sent in the request information.
The premonition I had felt turned out to be correct.
GET Requests That Fail
In the case of axios
Looking at the axios documentation, it is indeed stated as follows[1]
data is the data to be sent as the request body Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH'
import axios from 'axios'
const config = {
method: 'get',
url: 'https://api-request-example/api/fetch-data',
headers: {
'Content-Type': 'application/json',
'token': 'hogefugopiyo'
},
data: JSON.stringify({
'sample': 'hoge'
})
}
axios(config)
.then(...)
.catch(...)
In the case of fetch()
When using fetch, an error message like the following is explicitly displayed in the browser console [2]
Request with GET method cannot have body
const requestOptions = {
method: 'GET',
url: 'https://example.com/api/data',
headers: {
'Content-Type': 'application/json',
'token': 'hogefugopiyo'
},
data: JSON.stringify({
'sample': 'hoge'
})
}
fetch('https://example.com/api/data', requestOptions)
.then(...)
.catch(...)
Indeed, it seems to be clearly stated in the fetch() MDN documentation [3]
body - Note that it cannot be used if the method is GET or HEAD.
References
Discussion