0

我在使用 Mock Service Worker 的反应应用程序中进行了测试。我这样设置服务器:

 const server = setupServer(

  // https://api.github.com/search/users?q=${userName}&type=users&per_page=10&page=${pageNo}`,
  rest.get('https://api.github.com/search/users/', async (req, res, ctx) => {
    console.log('rest req.params', req.params) // {} empty object
    console.log('rest req.url.searchParams', req.url.searchParams) // {} empty object
    const users = search_data[1]
    return res(ctx.json(users))
  }),

  // https://api.github.com/users/${user}
  rest.get(`https://api.github.com/users/:user`, async (req, res, ctx) => {
    // console.log('rest req.params.user', req.params.user) // this works as it should
    return res(
      ctx.json(
        users_data[1].users.find((user) => user.login === req.params.user)
      )
    )
  })
)

上面的第一个 get 请求正在拦截被注释掉的 api 端点(它上面的那个)。我想在一个对象中获取查询参数,比如用户名,但返回的对象是空的。我究竟做错了什么?

截取的代码如下:

const searchGithubApi = (
  userName: string,
  pageNo: number = 1,
  signal: AbortSignal
) => {
  console.log('userName', userName) // I get the correct userName
  return fetch(
    `https://api.github.com/search/users?q=${userName}&type=users&per_page=10&page=${pageNo}`,
    {
      headers: {
        Accept: 'application/vnd.github.v3+json',
      },
      signal,
    }
  ).then((res) => res.json())
}  
4

2 回答 2

1

请参阅下面的链接,它解释得很好。 https://github.com/mswjs/msw/discussions/910

于 2021-09-13T04:13:51.747 回答
0

您应该使用URLSearchParams API 来检索请求查询参数:

req.url.searchParams.get('q')

注销req.url.searchParams将始终返回一个空对象,因为您实际上是在注销一个不将查询参数存储为其属性的类实例(因此您会看到一个空对象)。

于 2021-09-12T18:29:09.483 回答