Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:%5B%22id%22%5D%7D reason: Unexpected end of JSON input`

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading