The KNVB
The KNVB

Reputation: 3844

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

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=%7B%22list_info%22:%7B%22row_count%22:100%7D,%22fields_required%22:[%22id%22]%7D reason: Unexpected end of JSON input`

Upvotes: 1

Views: 1871

Answers (1)

Phil
Phil

Reputation: 164733

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 {
  //                          👇 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)
}

Upvotes: 2

Related Questions