Wondering how I can make a GET request to a JSON API using Node.js. I preferably want to use Express however it is not necessary, and for the output to be on a Jade page. I'm still completely new to Node.js and backend languages as a whole.
Replicating fetch() with 'node-fetch' package To install, run npm install node-fetch , and set up your code like this: const fetch = require('node-fetch'); let url = "https://www.reddit.com/r/popular.json"; let settings = { method: "Get" }; fetch(url, settings) . then(res => res.
At server side you will do: var url = require( "url" ); var queryString = require( "querystring" ); http. createServer( function (req, res) { // parses the request url var theUrl = url. parse( req.
Node.js has a built-in module to make API requests http The concept of handling asynchronous code has to be understood to make API requests. There are many utilities available to make API requests convenient. The module node-fetch implements the Fetch-API for Node.js.
Got is another popular HTTP request library for Node.js. It claims to be a “human-friendly and powerful HTTP request library for Node.js.” It also features a promise-based API, and HTTP/2 support and its pagination API are Got’s USPs.
Node.js has built-in modules to perform many HTTP (S)-related actions, one of which is the ability to make HTTP calls. Let’s get started with the native HTTP (S) option that comes baked in with Node.js as our first example. Node.js comes with both HTTP and HTTPS modules in the standard library.
Yes, if the data is JSON formatted it is very simple json (), but still, it's an extra step. Currently, the module supports HTTP by default and needs to be required for https, so const http = require ('http'); or const https=require ('https');.
var request = require('request');
request('<API Call>', function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
}
})
This will make an HTTP request to the API and upon success parse the response into JSON.
As far as getting the response onto a Jade page do you wish to do an API call (to your own server) and then use AngularJS/ jQuery/ another framework to fill in the information?
If you wish to add this to your own route consider embedding it like such:
var express = require('express');
var cors = require('cors');
var request = require('request');
var app = express();
app.use(express.bodyParser());
app.use(cors());
app.get('<Your Route>', function(req, res){
request('<API Call>', function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
// do more stuff
res.send(info);
}
})
});
app.listen(3000);
console.log("The server is now running on port 3000.");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With