How to make a post request using request module NodeJs express - node.js

How to make a proper post request to this endpoint. When I use the POSTMAN I get the correct response but when I call using the below function I get 503 error. The call seems to be fine according to me. I appreciate your help!!
const request = require('request');
const express = require('express');
// Initialize request
var img64Data = "/9j/4AAQSkZJRgABAQAAAQABAAD/2w… "; // Include the entire base64 encoding. // Shown Below in the next page
var send = {"img64": img64Data};
var api_address = "https://8n78hbwks0.execute-api.us-west-2.amazonaws.com/dev/";
// Make Post Request
module.exports = app => {
app.post('/axe', (req, res, next) => {
console.log("inside the axe");
request.post({
url: api_address,
body: JSON.stringify(send),
headers: {"Content-Type":"application/json"}
}, function (error, response, body) {
console.log("hiii");
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results) // View Results
}
});
});
};

You get a 503 Error https://en.wikipedia.org/wiki/List_of_HTTP_status_codes because your server doesn't reply any http code.
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results) // View Results
res.sendStatus(200);
} else {
res.sendStatus(response.statusCode);
}

Related

How to call rest api in express js

I am new in nodejs and I am using express js, I am calling REST API and want to show the response, but my problem is that the response is showing in console.log but I want to pass the body(response) in assistant.ask, where I am wrong here is my code:
var request = require('request');
let rawInput = function (assistant) {
let rawInput = assistant.getRawInput();
request.post(
'http://xxxxxxx.ngrok.io/api/v1/240/respond',
{ json: { query: rawInput } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
assistant.ask(body);
}
else{
console.log(error);
}
}
);

Wordpress API with Express and NODEJS

Is it possible to make an external http get request from Wordpress API using express?
Let's say I want to make a get request to http://demo.wp-api.org/wp-json/wp/v2/posts - This are a list of posts from wordpress.
Sample:
router.get('/posts', function(req, res){
I should make an external http get request here from wordpress api
("http://demo.wp-api.org/wp-json/wp/v2/posts")
Then I want to display the response as json
}
Update (I figure it out):
I use the request module, so to anyone whose having trouble with it. You can call this function inside your controller:
var express = require("express");
var request = require("request");
var router = express;
var getWPPost = function(req, res){
var headers, options;
// Set the headers
headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
// Configure the request
options = {
url: 'http://demo.wp-api.org/wp-json/wp/v2/posts/1',
method: 'GET',
headers: headers
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send({
success: true,
message: "Successfully fetched a list of post",
posts: JSON.parse(body)
});
} else {
console.log(error);
}
});
};
router.get('/post', function(req, res){
getWPPost(req, res);
}

Getting response from a website using Node.js

I am making a simple code in node using request to test if a website exist or not.
I want response if website exists with statusCode 200, if not then exit with statusCode 404
Here is my stuff
var http = require('http');
var request = require('request');
http.createServer(function (req , res) {
res.write("hello");
request('http://www.cutm.ac.in', function (error , response , body) {
if(!error && response == 200){
console.log(body);
}
else{
console.log("hdsa");
}
});
}).listen(9000);
console.log("started");
If I am doing
if(!error && response == 200)
it's not working, but when I remove response == 200, I am getting the html codes.
Any help
Try this.
var http = require('http');
var request = require('request');
http.createServer(function (req , res) {
res.write("hello");
request('http://www.cutm.ac.in', function (error , response , body) {
if(!error && response.statusCode == 200){
console.log(body);
}
else{
console.log("hdsa");
}
});
}).listen(9000);
console.log("started");
Always check statusCode to get response status

Unable to return body of request method in nodejs

I'm trying to get a JSON response via the request method and return the output so that i can store it in a variable when the function is called. when i log the response within the request method, it works fine. However when i return the output, it doesn't return.
var getAPIresponse = function(url) {
var request = require('request');
request(url, function(error, response, body) {
if(!error && response.statusCode == 200) {
console.log(body); // WORKS PERFECTLY
return body; // I Believe the issue is here
} else {
console.log("Error: "+ error);
}
});
};
router.get('/', function (req, res) {
var poolList = getAPIresponse("www.addAURL");
console.log(poolList); // DOESN'T WORK. REPORTS AS UNDEFINED
res.render('index', model); // THIS IS JUST SAYS HELLO WORLD
});
What your method actually does is run the following two lines
var request = require('request');
request(url, function(error, response, body) {
...and then fall out of the function right away at which point your calling code gets undefined back. The callback isn't called until the request is done, which may be much later.
To make it work, your function needs a callback too that is called when the function is actually complete, something like;
var getAPIresponse = function(url, cb) {
var request = require('request');
request(url, function(error, response, body) {
if(!error && response.statusCode == 200) {
console.log(body); // WORKS PERFECTLY
} else {
console.log("Error: "+ error);
}
cb(error, body);
});
};
router.get('/', function (req, res) {
var poolList = getAPIresponse("www.addAURL", function(err, poolList) {
// This is run in a callback once the request is done.
console.log(poolList);
res.render('index', model);
});
});
Another way would be to use promises which can clean up the code somewhat when the number of callbacks is getting out of hand.

How to render the results of an http request in Express?

Using Request and Express, how do I access the result of my http request for the purpose of rendering it?
var request = require('request');
var http = require('http');
exports.index = function(req, res){
var apiUrl = 'http://api.bitcoincharts.com/v1/weighted_prices.json';
request(apiUrl, function(err, res, data) {
if (!err && res.statusCode == 200) {
data = JSON.parse(data);
console.log(data);
res.render('index', { data: data });
}
});
};
As it is, the res I'm referring to within the request callback is the raw response object and I'm wondering how to call the response from my exports.index function without the request being inaccessible.
Just rename one of the arguments:
// either this:
exports.index = function(req, response) {
...
response.render(...);
};
// or this:
request(apiUrl, function(err, response, data) {
if (!err && response.statusCode == 200) {
data = JSON.parse(data);
console.log(data);
res.render('index', { data: data });
}
};

Resources