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.
Related
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
}
}
);
});
after a post request from an ajax call in angularjs, i want to send the request params from angularjs to an external api. I get all params i want. But I don't know, how i can make a new post request to the api, inside my nodejs url. I need this step to nodejs.
This is my Code
router.post({
url: '/user/:id/sw'
}, (req, res, next) => {
var userId = req.pramas.id;
var firstName = req.pramas.firstName;
var lastName = req.pramas.lastName;
var data = 'test';
res.send(200, data);
});
I found some solutions like this on: (just example code)
request({
uri: 'http://www.giantbomb.com/api/search',
qs: {
api_key: '123456',
query: 'World of Warcraft: Legion'
},
function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
res.json(body);
} else {
res.json(error);
}
}
});
but this doesn't work. How I can make a new Post Request with the req.params to an external api? Also i need a Response from the api..
Thanks for help and Ideas :)
Its req.params not req.pramas
Try this
var request = require('request');
router.post({
url: '/user/:userId/shopware'
}, (req, res, next) => {
var params = req.params;
request.get({
uri: 'http://www.giantbomb.com/api/search',
qs: params // Send data which is require
}, function (error, response, body) {
console.log(body);
});
});
Try this,
const request = require('request-promise')
const options = {
method: 'POST',
uri: 'http://localhost.com/test-url',
body: {
foo: 'bar'
},
json: true
// JSON stringifies the body automatically
};
request(options)
.then(function (response) {
// Handle the response
})
.catch(function (err) {
// Deal with the error
})
var request = require("request");
exports.checkstatus = async (req, res) => { //this is function line you can remove it
try {
var options = {
method: 'POST',
url: 'https://mydoamin/api/order/status',
headers:
{
signature: '3WHwQeBHlzOZiEpK4yN8CD',
'Content-Type': 'application/json'
},
body:
{
NAME: 'Vedant',
ORDERID: 'ORDER_ID1596134490073',
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body); //get your response here
});
} catch (error) {
return fail(res, error.message);
}
};
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);
}
I want to make a backend call to an external api's and populate my page with the results. What is the best way to do this?
The "request.get" call is asynchronous, so I understand the code below is erroneous. However, I have written it in that fashion so that I can explain what I want to actually do.
Further, I may have 5-6 external api, is there a way to make this asynchronous for every api but synchronous get call?
This is how my current code looks like:
var express = require('express');
var request = require('request');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
var body = getRawApiResponse("someURL");
console.log("Index >" + body);
res.render('index', { title: 'Express', api: "some", body: body});
});
function getRawApiResponse(api){
request.get({
uri: api,
},
function(error, response, body){
if (!error && response.statusCode === 200) {
console.log("Index > Raw Api Response: " + body);
} else {
console.log(error);
}
});
}
You can wrap getRawApiResponse() in a promise
function getRawApiResponse(api){
return new Promise(function(resolve, reject){
request.get({
uri: api,
},
function(error, response, body){
if (!error && response.statusCode === 200) {
resolve(body)
} else {
reject(error)
}
});
});
}
which resolves on success and rejects in case of an error then you can chain it inside the get request like
router.get('/', function(req, res, next) {
getRawApiResponse("someURL")
.then(function(body){
res.render('index', { title: 'Express', api: "some", body: body});
})
.catch(err){
// do something
}
});
Look into Promises or async/await. You can use them to call your async apis and wait for the response making the call synchronous.
http://bluebirdjs.com/docs/getting-started.html
A Sample code of async/ await which u can modify for ur purpose is as below:
try{
let orderDetails = await MongoHelper.findOneByCriteria(MongoCollections.ORDER,searchCriteria);
}catch(err){
return err;
}
MongoHelper.findOneByCriteria = (collectionName, criteria) => {
return new Promise((resolve, reject) => {
db.collection(collectionName).find(criteria).toArray()
.then((results) => {
if (results.length > 0) {
resolve(results[0]);
} else {
resolve(null);
}
});
});
}
The best way is to use Promises to avoid callbacks hell. If you can use node.js v7.6 or higher, it could be much easier with async/await.
router.get('/', function(req, res, next) {
getRawApiResponse("someURL")
.then(body => {
console.log("Index >" + body);
res.render('index', { title: 'Express', api: "some", body: body});
});
});
function getRawApiResponse(uri) {
return new Promise((resolve, reject) => {
request.get({ uri }, (error, response, body) => {
if (err) {
reject(err);
}
resolve(body);
});
});
}
In the example about I use promisification to return a promise from getRawApiResponse, but there is already a module which do the same https://github.com/request/request-promise.
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);
}