Simple API Calls with Node.js and Express
Solution 1
You cannot fetch stuff with Express, you should use Mikeal's request library for that specific purpose.
Installation: npm install request
The API for that library is very simple:
const request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
})
Edit: You're better of using this library instead of the http default one because it has a much nicer API and some more advanced features (it even supports cookies).
UPDATE: request has been deprecated, but there are some nice alternatives still such as 'got' or 'superagent' (look them up on npm).
Solution 2
You can use the http client:
var http = require('http');
var client = http.createClient(3000, 'localhost');
var request = client.request('PUT', '/users/1');
request.write("stuff");
request.end();
request.on("response", function (response) {
// handle the response
});
Also, you can set headers as described in the api documentation:
client.request(method='GET', path, [request_headers])
Solution 3
Required install two package.
npm install ejs
npm install request
server.js
var request = require('request');
app.get('/users', function(req, res) {
request('https://jsonplaceholder.typicode.com/users', function(error, response, body) {
res.json(body)
});
});
index.ejs
$.ajax({
type: "GET",
url: 'http://127.0.0.1:3000/posts',
dataType: "json",
success: function(res) {
var res_data = JSON.parse(res);
console.log(res_data);
}
});
Output
John
Flash and web developer with experience in online advertising and marketing.
Updated on July 21, 2022Comments
-
John almost 2 years
I'm just getting started with Node, APIs, and web applications.
I understand the basic workings of Node.js and Express, but now I want to start making calls to other service's APIs and to do stuff with their data.
Can you outline basic HTTP requests and how to grab/parse the responses in Node? I'm also interested in adding specific headers to my request (initially I'm using the http://www.getharvest.com API to crunch my time sheet data).
P.S. This seems simple, but a lot of searching didn't turn up anything that answered my question. If this is dupe, let me know and I'll delete.
Thanks!
-
Justin Helgerson over 10 yearsIn case anyone else comes across this, this method is deprecated.
-
Karthikeyan Velmurugan over 8 yearscan you please tell me, that is it necessary to end the request, like we will be using '.end()' for the http request?
-
alessioalex over 8 yearsI think that's only required for the native http client.
request
does that for you and exposes a friendlier interface. -
danefondo over 3 yearsAnyone coming across this, the 'request' library is deprecated.
-
ulou over 3 yearsKeep in mind that this library is already depracated (since Feb 2020).
-
KIYZ over 2 yearsrequest is now deprecated. npmjs.com/package/request