Simple API Calls with Node.js and Express - javascript

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!

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).

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])

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

Related

Node.js JavaScript Basic Get Request

Just installed node.js, and I'm having trouble sending basic get requests. I used to run things in chrome/firefox's console but wanted to branch out. What I am trying to do (as a test) is send a get request to a webpage, and have it print out some text on it.
In chrome's console, I would do something like this:
$.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(data) {
console.log($(data).find(".question-hyperlink")[0].innerHTML);
});
In node.js, how would I do that? I've tried requiring a few things and gone off a few examples but none of them worked.
Later on, I'll also need to add parameters to get and post requests, so if that involves something different, could you show how to send the request with the parameters {"dog":"bark"}? And say it returned the JSON {"cat":"meow"}, how would I read/get that?
You can install the request module with:
npm install request
And, then do this in your node.js code:
const request = require('request');
request.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(err, response, body) {
if (err) {
// deal with error here
} else {
// you can access the body parameter here to see the HTML
console.log(body);
}
});
The request module supports all sorts of optional parameters you can specify as part of your request for everything from custom headers to authentication to query parameters. You can see how to do all those things in the doc.
If you want to parse and search the HTML with a DOM like interface, you can use the cheerio module.
npm install request
npm install cheerio
And, then use this code:
const request = require('request');
const cheerio = require('cheerio');
request.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(err, response, body) {
if (err) {
// deal with error here
} else {
// you can access the body parameter here to see the HTML
let $ = cheerio.load(body);
console.log($.find(".question-hyperlink").html());
}
});

Javascript - How to make REST API Calls

I am trying to access Firebase Database using REST API. Using cURL i am able to retrive data. I am unable to do the same in javascript.
cURL
curl 'https://testproject123.firebaseio.com/subscription.json?auth=aabbccddeeff123'
Javascript
var request = require('request');
var options = {
url: 'https://testproject123.firebaseio.com/subscription.json?auth=aabbccddeeff123' };
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
} }
request(options, callback);
Note: The above code i am trying to run on Bluemix/OpenWhisk.
Kindly let me know how to fix this.
The structure of your action is a bit off for OpenWhisk. Javascript actions need to have a main method and you'll have to use whisk.async() and whisk.done() to make your (asynchronous) REST API call work as you'd expect it.
An example of how to call an external API using a Javascript action in OpenWhisk can be found here.

Node.js - multiple requests with cookies

I am building an app using Node.js. I am using the request package to make server-side GET requests. Specifically, I am making requests that use custom HTTP headers:
https://www.npmjs.com/package/request#custom-http-headers
The documentation shows how to make one request at a time. However, I need to make a request to two different API's. Does anyone have any idea how to do this? My current code for making one request:
var cookie = parseCookie.parseCookie(req.headers.cookie);
var cookieText = 'sid='+cookie;
var context;
function callback(error, response, body) {
var users = JSON.parse(body);
res.render('../views/users', {
context: users
});
}
var options = {
url: 'http://localhost:3000/api/admin/users/',
headers: {
host: 'localhost:3000',
connection: 'close',
cookie: cookieText
}
};
request(options, callback);
//need to make a request to another API.
As a side note, the reason I need to use custom HTTP headers is so I can include a cookie so my API can authenticate.
For flow control in nodejs, I would recommend you to use async
If you want to do in parallel without order of execution :
async.parallel([
function(callback) { request(apiCall1Options, callback); },
function(callback) { request(apiCall2Options, callback); }
], function(err, apiCallResults) { console.log(apiCallResults) })
If you need order, use async.waterfall.
Could be done as well by simply using plain callbacks, which I wouldnt recommend you using, or a promise library, like Q, or bluebird.

Making HTTP requests from server side

I have some code that is trying to get a JSON result from the Soundcloud API.
I registered an app, got the client id and such, and I'm trying to make a call like this:
var querystring = require('querystring');
var http = require('http');
var addr = 'http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=XXXXX';
var options = {
hostname: "api.soundcloud.com",
path: "/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=XXXXXx",
method: "GET",
headers: {
"Content-Type": "application/json"
}
}
var request = http.get(options, function(response) {
response.setEncoding('utf8');
response.on('data', function(chunk) {
console.log(chunk);
});
});
This produces a result that looks like this:
{"status":"302 - Found","location":"https://api.soundcloud.com/tracks/49931.json?client_id=xxxx"}
When I use the same URL in Chrome, I get the proper JSON info. How do I properly make this call from server side script?
The built-in http client does not handle redirects. However request does and has many other features the built-in client does not support out of the box.
Today I updated my own NodeJS Api-Wrapper Package for Soundcloud, which can be found here: https://www.npmjs.com/package/soundcloud-nodejs-api-wrapper
It does server side API communication, which includes data modification. No user popup window and redirect url is needed.
I did not found yet any other package having support for this in NodeJS.

Starting with Node.js and CouchDB without libraries like nano or cradle [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Getting ' bad_request invalid_json' error when trying to insert document into CouchDB from Node.js
The highest voted answer on
CouchDB and Node.js - What module do you recommend?
recommends not to use libraries such as nano or cradle for starting with Node.js and CouchDB.
However I haven't found any tutorial on how to perform standard operations for all DBMSes like create database, create table, add and view data etc. programmatically.
EDIT: (partial answer) after installing and starting CouchDB go to http://localhost:5984/_utils/script/couch.js.
You should start by reading the CouchDB book.
No idea why you don't want to use a module: I think you took an answer out of context (an answer that is probably one year old) and made your decision not to use a module.
That is not likely to be helpful to get stuff done. :) You are just repeating work that is done, and issues that have been fixed, etc.
If you want to learn CouchDB, read the book. You can read nano's source as it maps really closely to the API and should be easy to read, but the book is the full way to go.
If by any reason you decide you still want to implement your own module to do what others already do well, go for it :)
If instead you are looking for resources on using nano there are quite a few:
readme: github
screencast: couchdb and nano
article: nano - a minimalistic couchdb client for nodejs
article: getting started with node.js and couchdb
article: document update handler support
article: nano 3
article: securing a site with couchdb cookie authentication using node.js and nano
article: adding copy to nano
article: how to update a document with nano
article: mock http integration testing in node.js using nock and specify
article: mock testing couchdb in node.js with nock and tap
Thanks to Ruben Verborgh, I compiled micro-tutorial from several sources myself.
var http = require('http')
var sys = require('sys')
var couchdbPath = 'http://localhost:5984/'
request = require('request')
h = {accept: 'application/json', 'content-type': 'application/json'}
request(
{uri: couchdbPath + '_all_dbs', headers:h},
function(err, response, body) { console.log(sys.inspect(JSON.parse(body))); }
)
// add database
request(
{uri: couchdbPath + 'dbname', method:'PUT', headers:h},
function (err, response, body) {
if (err)
throw err;
if (response.statusCode !== 201)
throw new Error("Could not create database. " + body);
}
)
// Modify existing document
var options = {
host: "localhost",
port: 5984,
path: "/dbname",
headers: {"content-type": "application/json"},
method: "PUT"
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
//console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(JSON.stringify({
"_id":"rabbit",
"_rev":"4-8cee219da7e61616b7ab22c3614b9526",
"Subject":"I like Plankton"
}));
req.end();
I used following documentation:
http.request()
CouchDB Complete HTTP API Reference
Here are a few hands-on examples, thoughts and code-snippets which should help in your study
Simple Blog with Coffeescript, Express and CoudbDB
Thoughts on development using CouchDB and Nodejs
Bind CouchDB and Node.js
Getting Started with Node.js, Express and CouchDB - this link does not seem to be accessible now, but it seems a temporary issue.
Here's one on testing CouchDB - Mock testing CouchDB using Node.js
Hope it helps.
CouchDB is not an SQL database engine. It's in the family of the "NoSQL" ones.
You don't do select, you don't create tables, etc.
It's completely different.
It's actually using a REST API to work. Like, to access all the documents, you access them using an HTTP GET on the following URL: http://some.server/someDbName/_all_docs
For a more thorough introduction, I suggest looking for "CouchDB tutorial" on Google.
You'll find good links like this one or this one. (I'm not vouching for any, they just look good as an introduction.)
To make an http request in node.js, you can use the request method of the built-in http module. A shortcut method is http.get, which you can use like this:
var http = require( 'http' );
http.get( 'http://some.url/with/params', function( res ) {
// res has the values returned
});
Edit after reading your code:
Firstly, the doc you're using if outdated. Node is at v0.8, not 0.4.
Secondly, your request = require('request') must give some problems (does the module exist?). I don't think the first part is even executed.
Thirdly, just try a GET request for now. Something like:
var http = require( 'http' );
http.get( 'http://localhost:5984/_all_dbs', function( res ) {
console.log( res );
});
See if it's working. If it is, you already know how to use couchdb ;)
Lastly, your request at the end doesn't seem wrong. Maybe it's related to require('request') though, so I don't know.

Categories