Simple API Calls with Node.js and Express
You cannot fetch stuff with Express, you should use Mikeal's request library for that specific purpose.
The API for that library is very simple:
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. }})
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).
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