HTTP GET Request in Node.js Express
Here is a snippet of some code from a sample of mine. It's asynchronous and returns a JSON object. It can do any form of GET request.
Note that there are more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:
const http = require('http');
const https = require('https');
/**
* getJSON: RESTful GET request returning JSON object(s)
* @param options: http options object
* @param callback: callback to pass the results JSON object(s) back
*/
module.exports.getJSON = (options, onResult) => {
console.log('rest::getJSON');
const port = options.port == 443 ? https : http;
let output = '';
const req = port.request(options, (res) => {
console.log(`${options.host} : ${res.statusCode}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
output += chunk;
});
res.on('end', () => {
let obj = JSON.parse(output);
onResult(res.statusCode, obj);
});
});
req.on('error', (err) => {
// res.send('error: ' + err.message);
});
req.end();
};
It's called by creating an options object like:
const options = {
host: 'somesite.com',
port: 443,
path: '/some/path',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
And providing a callback function.
For example, in a service, I require the REST module above and then do this:
rest.getJSON(options, (statusCode, result) => {
// I could work with the resulting HTML/JSON here. I could also just return it
console.log(`onResult: (${statusCode})\n\n${JSON.stringify(result)}`);
res.statusCode = statusCode;
res.send(result);
});
UPDATE
If you're looking for async
/await
(linear, no callback), promises, compile time support and intellisense, we created a lightweight HTTP and REST client that fits that bill:
Microsoft typed-rest-client
Nodejs + Express: How to get an element which made an HTTP GET request?
You need to pass the information about the row/item that makes the GET
request, that is a must.
Now with Express
there are a couple of ways to do this: Express routing
.
1. Defining route params: req.params
GET
Request: /documents/table/file/345
(345 is the row identifier name or id
etc)
At nodejs express end:
router.get("/documents/table/file/:id", (req, res) => {
/*request parameter with this kind of route sits in req.params*/
console.log(req.params);
const requestedId = req.params.id;
});
2. Sending as query string parameters: req.query
GET
Request: /documents/table/file?id=345
At nodejs express end:
router.get("/documents/table/file/", (req, res) => {
/*request parameter with this kind of route sits in req.query*/
console.log(req.query);
const requestedId = req.query.id;
});
Making external get request with Express
The accepted answer is good, but in case anyone comes across this question later, let's keep in mind that as of February, 2020, request is now deprecated.
So what can we do? We can use another library. I would suggest Axios.
Install it and do something like:
const axios = require('axios')
const url = "https://example.com"
const getData = async (url) => {
try {
const response = await axios.get(url)
const data = response.data
console.log(data)
} catch (error) {
console.log(error)
}
}
getData(url)
NodeJS express make get request
If you want simple requests, don't use the express module, but for example request :
var 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.
}
})
Related Topics
Angular 2: How to Detect Changes in an Array? (@Input Property)
How to Conditionally Add Attributes to React Components
How to Detect If Flash Is Installed and If Not, Display a Hidden Div That Informs the User
Get Caret (Cursor) Position in Contenteditable Area Containing HTML Content
Why Array.Indexof Doesn't Find Identical Looking Objects
Password Encryption at Client Side
How to Return a View from an Ajax Call in Laravel 5
Scrolltop Animation Without Jquery
How to Tell If a Browser Supports <Input Type='Date'>
How to Open New Tab in JavaScript Without Switching to the New Tab
Differencebetween Window, Screen, and Document in JavaScript
How to Find the Array Index with a Value
Getting Blob Data from Xhr Request
Reading Client Side Text File Using JavaScript
Overriding a JavaScript Function While Referencing the Original
Keep Input Value After Refresh Page
How to Resize Twitter Bootstrap Modal Dynamically Based on the Content