node-fetch提交GET请求时出现问题

An problem occur when submit a GET Request by node-fetch

我正在使用 node-fetch 从 REST 中获取数据 API。

这是我的代码:

this.getUserList = async (req, res) => {
  const fetch = require('node-fetch');
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
  let params = {
    "list_info": {
      "row_count": 100
    }
  } 
  
  fetch('https://server/api/v3/users?input_data=' + JSON.stringify(params), {
    headers:{
      "TECHNICIAN_KEY": "sdfdsfsdfsd4343323242324",
      'Content-Type': 'application/json',
    },                  
    "method":"GET"
  })
    .then(res => res.json())
    .then(json => res.send(json))
    .catch(err => console.log(err));
}

它工作正常。

但是,如果我更改以下语句:

let params = {"list_info":{"row_count": 100}}

let params = {"list_info":{"row_count": 100}, "fields_required": ["id"]}

提示如下错误信息:

FetchError: invalid json response body at https://server/api/v3/users?input_data=%7B%22list_info%22:%7B%22row_count%22:100%7D,%22fields_required%22:[%22id%22]%7D reason: Unexpected end of JSON input`

问题是您 URL-encoding 不是您的查询字符串。这可以使用 URLSearchParams.

轻松完成

此外,GET 请求没有任何请求 body,因此不需要 content-type header。 GET 也是 fetch()

的默认方法
const params = new URLSearchParams({
  input_data: JSON.stringify({
    list_info: {
      row_count: 100
    },
    fields_required: ["id"]
  })
})

try {
  //                           note the ` quotes
  const response = await fetch(`https://server/api/v3/users?${params}`, {
    headers: {
      TECHNICIAN_KEY: "sdfdsfsdfsd4343323242324",
    }
  })

  if (!response.ok) {
    throw new Error(`${response.status}: ${await response.text()}`)
  }

  res.json(await response.json())
} catch (err) {
  console.error(err)
  res.status(500).send(err)
}