Post request to external api - node.js

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

Related

I can't save the response of a request request in node.js

I created a login function that receives the mail and the pass, to receive the jwt. I have tried that the function returns the jwt but I have not succeeded.
This is the method that I have developed, it has a post request that sends the mail and pass parameters. in the resp variable I try to save the request response, but when invoking the function it prints :
undefined.
login(mail, pass) {
var options = {
'method': 'POST',
'url': 'https://inventario.demos.adlnetworks.com/api/login',
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify({ "email": mail, "password": pass })
};
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
resp = response.body;
});
return resp;
}
The problem is that "request" is an async function. You can't do this
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
resp = response.body;
});
return resp;
Because "resp" always be undefined. You would need to do something like this
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
return response.body;
});
But it wont work for you.
The short and easy solution is change the library to make http request, and use "async" and "await" to use easily async functions.
For example:
const fetch = require('node-fetch');
async function main(){
const data = await login();
console.log(data);
}
async function login(){
const url = "https://jsonplaceholder.typicode.com/posts";
const data = {
title: 'foo22222',
body: 'ba222r',
userId: 1
};
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
const json = await response.json()
return json;
}
main();
In this case i use "node-fetch" library and consume a backend (in login function) that create a post and return its response.

how to get data outside request

I have a scenario where i need to take response (body) of request method outside request. How can i do it?
request.post({
url: 'http://localhost/api/messages',
form: { key: message }
}, function (err, httpResponse, body) {
tmsg = body;
})
console.log(tmsg);
I need this tmsg outside for next processing, Actual scenario is as below.
app.post('/incomemsg', function (req, res) {
var mediaCount = req.body.NumMedia;
if (mediaCount == 0) {
//var twiml = getResponse(message);
var twiml = new MessagingResponse();
request.post({
url: 'http://localhost:3978/api/messages',
form: { key: message }
}, function (err, httpResponse, body) {
tmsg = body;
})
console.log(tmsg);
}else {
//dosomething which outputs tmsg
}
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(tmsg.toString());
});
The problem is you are trying to assign value to a global variable in request.post's callback() which is only called after request.post is executed by Asynchronous logic(API calls are all async), so a better way would be to promisify request.post and await the request.post to make it seem synchronous.
const requestPromisified = requestObject =>
new Promise((resolve, reject) => {
request.post(requestObject, function(err, httpResponse, body) {
if (err) {
reject(err);
}
resolve(body);
});
});
const body = await requestPromisified({
method: "POST",
url: "http://localhost/api/messages",
form: { key: message }
});
You only can do something with tmsg when you made the request so you need to rearrange your code like this:
app.post('/incomemsg', function (req, res) {
var mediaCount = req.body.NumMedia;
var twiml = new MessagingResponse();
request.post({
url: 'http://localhost:3978/api/messages',
form: { key: message }
}, function (err, httpResponse, body) {
tmsg = body;
console.log(tmsg);
if (mediaCount === 0) {
//do something with tmsg
} else {
//do something else with tmsg
}
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(tmsg.toString());
});
});
Otherwise tmsg will be null because there was no request made to fill that variable.

HTTP POST with node.js and request library isn't outputting anything

I'm just testing to see if my POST request to a website works, but it isn't outputting anything. When I use RunKit, it shows an output, but not in my powershell. Am I doing something wrong or is there no output? How can I make it show the output? Here is my code:
var request = require('request');
request.post(
'My_API_URL',
{ json: { "text":"this is my text" } },
function (error, response, body) {
console.log(body);
}
);
What i suggest you, is to update your code like this and try again:
var request = require('request');
var options = {
uri: 'My_API_URL',
method: 'POST',
json: {
"text":"this is my text"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
Let me know if the result is the same.
Check this link. You should do post requests like this:
var request = require('request');
var body = JSON.stringify({
client_id: '0123456789abcdef',
client_secret: 'secret',
code: 'abcdef'
});
request.post({
url: 'https://postman-echo.com/post',
body: body,
headers: {
'Content-Type': 'application/json'
}},
function (error, response, body) {
console.log(body);
}
);

Unable to access response object data outside the function in node js

I am using node js and making a call to spotify API and receive the response in body object, as shown in below code:
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
console.log(body)
});
This gives me output:
But now when I try to access the body object outside the function I get undefined. I think the problem is that I am making an asynchronous call and so before the response is received the statements where I make use of body variable outside function are executed. But I am a bit confused about how to get to the solution.
Any help is appreciated
Edit:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
And it gives the output:
Use promise.
You can try following:
const apiCall = () => {
return new Promise((resolve, reject) => {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
if(error) reject(error);
console.log(body);
resolve(body);
});
});
}
apiCall().then((body) => {
// do your things here
})
.catch((err) => console.log(err));

Request within a request in nodejs

I am using request library in nodejs. I need to call new url within the request but I am not able to join the response as it is asynchronouse. How do I send variable a as in below request containing result of request within a request.
request({
url: url,
json: true
}, function (error, response, body) {
var a = [];
a.push(response);
for (i = 0; i < a.length; i++) {
if (a.somecondition === "rightcondition") {
request({
url: url2,
json: true
}, function (error, response, body) {
a.push(response);
});
}
}
res.send(a);
});
Your code seems almost right for what you want. You are just sending the response in the wrong callback. Move it so it only sends after the second request has completed:
request({
url: url,
json: true
}, function (error, response, body) {
var a = [];
a.push(response);
request({
url: url2,
json: true
}, function (error, response, body) {
for(i=0;i<a.length;i++){
if(a.somecondition === "rightcondition"){
a.push(response);
}
}
res.send(a); // this will send after the last request
});
});
You can use async waterfall
'use strict';
let async = require('async');
let request = require('request');
async.waterfall([function(callback) {
request({
url: url,
json: true
}, function(error, response, body) {
callback(error, [response]);
});
}, function(previousResponse, callback) {
request({
url: url2,
json: true
}, function(error, response, body) {
for(i=0;i<previousResponse.length;i++){
if(previousResponse.somecondition === "rightcondition"){
previousResponse.push(response);
}
}
callback(error, previousResponse);
});
}], function(err, results) {
if (err) {
return res.send('Request failed');
}
// the results array will be final previousResponse
console.log(results);
res.send(results);
});

Resources