Simple API Calls with Node.js and Express

Javascriptnode.jsAjaxApiExpress

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

> 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

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - JavascriptalessioalexView Answer on Stackoverflow
Solution 2 - JavascriptNicolas ModrzykView Answer on Stackoverflow
Solution 3 - JavascriptRam PukarView Answer on Stackoverflow