Search code examples
javascriptnodes

Javascript node-fetch usage


I can get the data by request from this code.

let request = require('request');
let options = {
   'method': 'POST',
   'url': 'https://example.com/api',
   'headers': {
       'Content-Type': 'application/x-www-form-urlencoded'
   },
   form: {
       'client_id': '12345678',
       'client_secret': 'abcdefg'
   }
};
request(options, function (error, response) {
   if (error) throw new Error(error);
   console.log(response.body);
});

However, I got '404.00.001' when I use "fetch" to access the same API. Is there any thing wrong in this code?

const fetch = require("node-fetch");

const url = "https://example.com/api";

var headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

var data = JSON.stringify( {
  'client_id': '12345678',
  'client_secret': 'abcdefg'
});

fetch(url, {method: 'POST', headers: headers, body: data})
  .then(response => response.json())
  .then((resp) => {
     console.log(resp);
  })
  .catch(error => console.error('Unable to fetch token.', error));

Solution

  • 'Content-Type': 'application/x-www-form-urlencoded' does not say JSON so why do you have var data = JSON.stringify?

    The documentation tells you how to encode data as form parameters.

    const { URLSearchParams } = require('url');
    
    const params = new URLSearchParams();
    params.append('a', 1);