Why the req.url.searchParams parameters object is empty when I test two get requests using Mock Service Worker? #910
-
Environment
Request handlers// Example of declaration. Provide your code here.
import { setupServer } from 'msw/node'
import { rest } from 'msw'
const server = setupServer(
// https://api.github.com/search/users?q=${userName}&type=users&per_page=10&page=${pageNo}`,
// https://api.github.com/users/${user}
rest.get('https://api.github.com/search/users', async (req, res, ctx) => {
const query = req.url.searchParams
// console.log('query', query) // empty {}
// console.log('rest req', req) // empty {}
// console.log('rest req.params', req.params) // empty {}
console.log('rest req.url.searchParams', req.url.searchParams) // empty {}
const users = search_data[0]
return res(ctx.json(users))
}),
rest.get(`https://api.github.com/users/:user`, async (req, res, ctx) => {
// console.log('rest req.params.user', req.params.user) // it works fine
return res(
ctx.json(
users_data[count].users.find((user) => user.login === req.params.user)
)
)
})
)
beforeAll(() => server.listen())
afterAll(() => server.close()) Actual request
Current behaviorIn the first handler I am expecting to get the query parameters in the request object, like the userName, but the returned object is empty. What am I doing wrong? Expected behaviorI am expecting to get all the query parameters in the request object from the api endpoint below (everything after question mark). |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey, @E01T. First thing to clarify, your example feature two distinct things:
Path parameters are exposed under rest.get('/users/:id', (req, res, ctx) => {
req.params.id // where "id" is taken from ":id"
}) Query parameters are exposed under a URLSearchParams instance, which is not an object. To access a query paramete you must call the rest.get('https://api.github.com/search/users', async (req, res, ctx) => {
// given "/search/users?q=E01T"
req.url.searchParams.get('q') // "E01T"
}) Note that logging out the console.log(req.url.searchParams) // {}
console.log(req.url.searchParams.get('q')) // "E01T" |
Beta Was this translation helpful? Give feedback.
Hey, @E01T.
First thing to clarify, your example feature two distinct things:
/search/users?a=1&b=2
("a" and "b");/users/:id
("id").'Path parameters are exposed under
req.params
object and are available based on the parameter name you give after the semicolon:Query parameters are exposed under a URLSearchParams instance, which is not an object. To access a query paramete you must call the
.get()
method on the said instance and provide it with the query parameter name: