【问题标题】:An problem occur when submit a GET Request by node-fetch通过 node-fetch 提交 GET 请求时出现问题
【发布时间】:2022-01-16 14:32:48
【问题描述】:

我正在使用 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: https://server/api/v3/users?input_data=%7B%22list_info%22:%7B%22row_count%22:100%7D,%22fields_required%22:[%22id 的 json 响应正文无效%22]%7D 原因:JSON 输入意外结束`

【问题讨论】:

    标签: node.js fetch-api


    【解决方案1】:

    问题是您没有对查询字符串进行 URL 编码。这可以使用URLSearchParams 轻松完成。

    此外,GET 请求没有任何请求正文,因此不需要内容类型标头。 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)
    }
    

    【讨论】:

    • 是的,我用错了单引号,对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多