Wordpress API with Express and NODEJS - node.js

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);
}

Related

How to pass data between routes in express.js

hope someone can help me. Can't find a solution. Maybe I'm also just on the wrong way?
It's a simple express setup and I'm quite new.
I get a response from a request and want to pass a variable/the data from the response to the next route into the URL.
So one parameter in the next URL should be dynamical depending on the response of the first call.
here my whole code:
My problem is where you can see the const sendoutID
const express = require("express");
const app = express();
const request = require("request");
const bodyParser = require("body-parser");
const port = 3001;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Create Sendout
app.post("/createSendout", (req, res, next) => {
request.post(
{
url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
body: JSON.stringify(req.body),
headers: {
"Content-Type": "application/json",
"X-API-KEY": "xxxx-xxx-xxxx-xxx-xxxxxxx",
},
},
function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results.CreateSendoutResult.SendoutId); // View Results
// I want this data "results.CreateSendoutResult.SendoutId" passing to the next route
}
}
);
});
/* here the variable is just hard coded for now but
I want to pass it in the URL from my previous route
to the next route see below at + sendoutID +..*/
const sendoutId = 389125;
// Add Respondent
app.post("/addRespondent", (req, res, next) => {
request.post(
{
url:
"https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
sendoutId +
"/respondents",
body: JSON.stringify(req.body),
headers: {
"Content-Type": "application/json",
"X-API-KEY": "xxxxxx-xxx-xxx-xxx-xxxxxxxx",
},
},
function (error, response, body) {
console.log(response);
//console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results); // View Results
}
}
);
});
app.listen(port, () => {
console.log(`app listening at http://localhost:${port}`);
});
To pass to the next route you can assign results.CreateSendoutResult.SendoutId to req.body
req.body.SendoutId = results.CreateSendoutResult.SendoutId;
Then you can use that SendoutId in next route.
You can pass that variable inside next()
next(results.CreateSendoutResult.SendoutId);
In the next route you can access it by calling:
function nextRoute(SenderId, req, res, next)
Edited:
const express = require("express");
const app = express();
const request = require("request");
const bodyParser = require("body-parser");
const port = 3001;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Create Sendout
app.post("/createSendout", (req, res, next) => {
request.post(
{
url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
body: JSON.stringify(req.body),
headers: {
"Content-Type": "application/json",
"X-API-KEY": "xxxx-xxx-xxxx-xxx-xxxxxxx",
},
},
function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results.CreateSendoutResult.SendoutId); // View Results
// I want this data "results.CreateSendoutResult.SendoutId" passing to the next route
req.SendoutId = results.CreateSendoutResult.SendoutId;
}
}
);
}, addRespondent);
/* here the variable is just hard coded for now but
I want to pass it in the URL from my previous route
to the next route see below at + sendoutID +..*/
const sendoutId = 389125;
// Add Respondent
app.post("/addRespondent", addRespondent);
function addRespondent(req, res, next) => {
request.post(
{
url:
"https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
req.sendoutId +
"/respondents",
body: JSON.stringify(req.body),
headers: {
"Content-Type": "application/json",
"X-API-KEY": "xxxxxx-xxx-xxx-xxx-xxxxxxxx",
},
},
function (error, response, body) {
console.log(response);
//console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results); // View Results
}
}
);
}
app.listen(port, () => {
console.log(`app listening at http://localhost:${port}`);
});
You should be using a middleware function.
What is a middleware function?
-> it's just a function that runs in the middle that is (before a request hits the route and ends before a request completes.Express Documentation for writing middlewares.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function.NOTE middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging..
Advantage of using a middleware function -> "you can use this function for any other request too in the future", use it in other modules".
2)
const captureSendOutIDMiddleware = async (req, res, next) => {
try {
req.SendOutID=results.CreateSendoutResult.SendoutId; //changed "const req" to just req.
next();
} catch (error) {
res.status(401).send({
error: 'NO SEND OUT ID'
})
}
app.post("/CreateSendOut",captureSendOutIDMIddleware,async(req, res) =>{
//do your operation
});
app.post("/addRespondent",async(req,res)=>{
const capturedSendoutID=req.SendoutID;
console.log(capturedSendoutID);
//do you operations
});
Thanks for your help.
I found now another solution which works as well as I found another issue. Don't know if it was also a cause for why it didn't work, or why your solutions didn't work. But I used app.set() and app.get to pass the data.
The other issue was, that now, with app.set() and app.get() it sometimes worked, sometimes not. So I set a timeout on the call in the frontend, which executes the api requests. Just to have a bit time between.
here is my new code
// Create Sendout
app.post("/createSendout", (req, res, next) => {
request.post(
{
url: "https://www.something.com/api/v1.2/surveys/904211/sendouts",
body: JSON.stringify(req.body),
headers: {
"Content-Type": "application/json",
"X-API-KEY": "xxxxxx-xxx-xx-xxxx-xxxxx",
},
},
function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results.CreateSendoutResult.SendoutId); // View Results
app.set("surveyId", results.CreateSendoutResult.SendoutId); // new added line
}
}
);
});
// Add Respondent
app.post("/addRespondent", (req, res, next) => {
const surveyId = app.get("surveyId"); // new added line
request.post(
{
url:
"https://www.something.com/api/v1.2/surveys/904211/sendouts/" +
surveyId +
"/respondents",
body: JSON.stringify(req.body),
headers: {
"Content-Type": "application/json",
"X-API-KEY": "xxxxxx-xxx-xxxx-xxxx-xxxxxxxx",
},
},
function (error, response, body) {
console.log(response);
//console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results); // View Results
}
}
);
});

How to hit third party API form node server.

IndiaSMS is a thirdparty providing sms service I want to hit this api form node server. Any way to request to third party api. Please help..
var express = require('express');
var router = express.Router();
exports.sendOTP = function (userInfo, callback) {
console.log(userInfo);
console.log('Inside SendOTP usin indaSMS');
var indiasmsURL = 'https://app.indiasms.com/sendsms/sendsms.php?username=user&password=pass&type=TEXT&sender=Alerts&mobile=' + userInfo.mobilenumber + '&message=Your%20OTP%20for%203DClubHouse%20is%20' + userInfo.otp + '';
console.log(indiasmsURL);
router.get(indiasmsURL,
function(req, res, next) {
console.log('--------------------------');
console.log(res);
console.log('--------------------------');
})
callback('hello');
};
Thnaks in advance.
This is Mikeal's request library see link here very useful
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
})
Using axios:
axios.get('https://app.indiasms.com/sendsms/sendsms.php', {
params: {
username: user,
password: pass,
type: 'TEXT',
//...
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Or using async/await, you can simply:
let response = await axios.get(indiasmsURL);
if (response.status == 200) {
//console.log(`CC status ${response.status}: `, response.data)
}
You can build your URI like above (stored in indiasmsURL) or specify them in the params of the request if you would prefer.
I would suggest snekfetch or request.

How to make a post request using request module NodeJs express

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);
}

Node - Simple xml API Request

I'm using the latest node.js (and express) to make an API call to a site that returns... XML... Ugh >_>.
I've scowered the web and found a million different ways, but I don't know the latest, most up to date / best way to make a request and get a response in node/express.
I tried using https://github.com/request/request and did the following:
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
var token = request
.get('some-website.com/api/stuff')
.on('response', function(response) {
console.log(response.statusCode);
console.log(response.headers['content-type']);
});
sendJsonResponse(res, 200, token);
in the console.log statements I get 200 and then application/xml;charset=utf-8.
But on my page I don't get the xml I'm looking for. Any ideas? I've tried using https://github.com/Leonidas-from-XIV/node-xml2js to attempt to "parse" the response, in case node just can't handle the xml response, but to no avail.
var xml2js = require('xml2js');
parser.parseString(response, function(err, result) {
console.dir(result);
console.log('Done');
});
Any help on accessing an API using Node and actually using the XML response, please?
EDIT ANSWER
For the Node.js request and xml parsing of the returned xml content:
var request = require('request');
var xml2js = require('xml2js');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
/* GET XML Content*/
module.exports.dsRequest = function(req, res) {
var parser = new xml2js.Parser();
request('url_for_xml_request', function(error, response, body) {
parser.parseString(body, function(err, result) {
sendJsonResponse(res, 200, result);
});
});
};
I think this will work, because request is async, you should write like below:
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
request.get('http://some-website.com/api/stuff', function (err,response, body) {
sendJsonResponse(res, 200, body);
});

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