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

Time:12-13

I am using node-fetch to fetch data from REST API.

Here is my code:

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));
}

It works fine.

However, if I change the following statement:

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

To

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

It prompts the following error message:

FetchError: invalid json response body at https://server/api/v3/users?input_data={"list_info":{"row_count":100},"fields_required":["id"]} reason: Unexpected end of JSON input`

CodePudding user response:

The problem is that you are not URL-encoding your query string. This can be easily accomplished using URLSearchParams.

Also, GET requests do not have any request body so do not need a content-type header. GET is also the default method for fetch()

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

try {
  //                                     
  • Related