Node.js 如何在nock回调中获取查询参数

Node.js 如何在nock回调中获取查询参数,node.js,nock,Node.js,Nock,我想访问nock reply回调中的查询参数 公开的请求对象包含将它们作为字符串的路径。但是我希望以映射的形式访问它们,这样我就不必解析字符串了 const scope = nock('http://www.google.com') .get('/cat-poems') .reply(function(uri, requestBody) { console.log('path:', this.req.path) console.log('headers:', this.r

我想访问nock reply回调中的查询参数

公开的请求对象包含将它们作为字符串的路径。但是我希望以映射的形式访问它们,这样我就不必解析字符串了

const scope = nock('http://www.google.com')
  .get('/cat-poems')
  .reply(function(uri, requestBody) {
    console.log('path:', this.req.path)
    console.log('headers:', this.req.headers)
    // ...
  })
我希望查询参数是我可以访问的单独映射
有人知道实现这一点的方法吗?

应答函数中的
this.req
的值是一个稍微修改过的实例

不幸的是,对于您的用例,
ClientRequest
并没有提供一种仅访问查询参数的简单方法。但是您可以访问完整路径,从中可以解析查询参数

const nock = require('nock')
const http = require('http')
const url = require('url')

const scope = nock('http://www.google.com')
  .get('/cat-poems')
  .query(true)
  .reply(function(uri, requestBody) {
    const parsed = new url.URL(this.req.path, 'http://example.com')
    console.log('query params:', parsed.searchParams)
    return [200, 'OK']
  })

const req = http.get('http://www.google.com/cat-poems?page=12')

// output >> query params: URLSearchParams { 'page' => '12' }
正在记录的对象是一个实例


使用构造函数是目前首选的方法,因此我在示例中使用了它。请记住,
URL
不会单独解析相对路径,它需要一个原点,但由于您最终不关心主机,它可能是一个伪值(因此使用“example.com”)。

应答函数中的
this.req
的值是一个稍微修改过的实例

不幸的是,对于您的用例,
ClientRequest
并没有提供一种仅访问查询参数的简单方法。但是您可以访问完整路径,从中可以解析查询参数

const nock = require('nock')
const http = require('http')
const url = require('url')

const scope = nock('http://www.google.com')
  .get('/cat-poems')
  .query(true)
  .reply(function(uri, requestBody) {
    const parsed = new url.URL(this.req.path, 'http://example.com')
    console.log('query params:', parsed.searchParams)
    return [200, 'OK']
  })

const req = http.get('http://www.google.com/cat-poems?page=12')

// output >> query params: URLSearchParams { 'page' => '12' }
正在记录的对象是一个实例

使用构造函数是目前首选的方法,因此我在示例中使用了它。请记住,
URL
不会单独解析相对路径,它需要一个原点,但由于您最终不关心主机,它可能是一个伪值(因此使用“example.com”)