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
}
}
);
});
Related
Front end => Middel service => End service
My front end sends a file to my nodejs service by doing this:
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
resolve(xmlHttp.responseText);
}
}
var data = new FormData();
data.append('file', event.target.files[0]);
xmlHttp.open('POST', '.../utUploadFile');
xmlHttp.send(data);
My End service then catches this and saves the file:
app.post('/utUploadFile', async (request, response, next) => {
const form = new formidable.IncomingForm();
form.parse(request, async function (err, fields, files) {
...save the 'files'
});
});
My question is, how do I add a middle layer to this, how to I just take the front end request, and pass the same thing on to the End service to do its work:
const http = require('request');
...
app.post(`/utUploadFile`, (request, response, next) => {
http.post({
headers: {'content-type': 'multipart/form-data'},
url: `.../utUploadFile`,
body: JSON.stringify(request.body)
}, (err, res, body) => {
});
});
I wanted to get the result from controller to route then I will render is to view using NodeJS.
var request = require('request');
var crypto = require('crypto');
username = "hello#.com.ph";
password = 123124123;
auth = "Basic " + Buffer.from(username + ":" + password).toString("base64");
exports.textname = function(req, res, next) {
request.post({
url : 'https://urlsample/api/getlist',
headers : {
"Authorization" : auth
}
}, function (error, response, body) {
return res.json(body);
});
};
In the code above, the anonymous function you pass on to request.post as the second parameter is a callback, and as such what you return from it is discarded. To return the body of the response, you should call next() after res.json(body):
// code from above...
exports.textname = function(req, res, next) {
request.post({
url : 'https://urlsample/api/getlist',
headers : {
"Authorization" : auth
}
}, function (error, response, body) {
res.json(body);
next();
});
};
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.
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);
}
};
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 });
}
};