Is there a way to extract "body" from the request function? - node.js

Is there a way to extract "body" from the request function?
var request = require("request");
var options = {
method: "POST",
url: "https://dev-5j3doydu.au.auth0.com/oauth/token",
headers: { "content-type": "application/json" },
body:client_id
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
return body;
});

Related

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

How to get post request to display in the console

//Need some help on api in console. I need help figiuring this out
var options = { method: 'POST',
url: URL + 'i/pushes/prepare?api_key=411f2297c3b58651019b3086e17bbfc7',
qs: { api_key: '411f2297c3b58651019b3086e17bbfc7' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
//get request
var options = { method: 'GET',
url: URL + 'o?method=devices&api_key=411f2297c3b58651019b3086e17bbfc7&app_id=5bb537f0b5af9c065041f52d',
qs: { app_id: '5bb537f0b5af9c065041f52d', api_key: '411f2297c3b58651019b3086e17bbfc7', method: 'devices' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log("DEVICE DATAS+++++++++++++++++++++++++++++++++++++++++++++++++")
console.log(JSON.parse(body));
console.log("Device info", ["2018"]["4"])
});
//Please any help is appreciated
Use JSON.stringify to get your response data like this,
console.log(JSON.stringify(body));
Alternatively you can use console.dir like this where you don't have to use JSON.stringify,
console.dir(body);
Hope this helps!

Post request to external api

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

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

POST data with request module on Node.JS

This module is 'request https://github.com/mikeal/request
I think i'm following every step but i'm missing an argument..
var request = require('request');
request.post({
url: 'http://localhost/test2.php',
body: "mes=heydude"
}, function(error, response, body){
console.log(body);
});
on the other end i have
echo $_POST['mes'];
And i know the php isn't wrong...
EDIT: You should check out Needle. It does this for you and supports multipart data, and a lot more.
I figured out I was missing a header
var request = require('request');
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/test2.php',
body: "mes=heydude"
}, function(error, response, body){
console.log(body);
});
When using request for an http POST you can add parameters this way:
var request = require('request');
request.post({
url: 'http://localhost/test2.php',
form: { mes: "heydude" }
}, function(error, response, body){
console.log(body);
});
I had to post key value pairs without form and I could do it easily like below:
var request = require('request');
request({
url: 'http://localhost/test2.php',
method: 'POST',
json: {mes: 'heydude'}
}, function(error, response, body){
console.log(body);
});
If you're posting a json body, dont use the form parameter. Using form will make the arrays into field[0].attribute, field[1].attribute etc. Instead use body like so.
var jsonDataObj = {'mes': 'hey dude', 'yo': ['im here', 'and here']};
request.post({
url: 'https://api.site.com',
body: jsonDataObj,
json: true
}, function(error, response, body){
console.log(body);
});
var request = require('request');
request.post('http://localhost/test2.php',
{form:{ mes: "heydude" }},
function(error, response, body){
console.log(body);
});
Install request module, using npm install request
In code:
var request = require('request');
var data = '{ "request" : "msg", "data:" {"key1":' + Var1 + ', "key2":' + Var2 + '}}';
var json_obj = JSON.parse(data);
request.post({
headers: {'content-type': 'application/json'},
url: 'http://localhost/PhpPage.php',
form: json_obj
}, function(error, response, body){
console.log(body)
});
I have to get the data from a POST method of the PHP code. What worked for me was:
const querystring = require('querystring');
const request = require('request');
const link = 'http://your-website-link.com/sample.php';
let params = { 'A': 'a', 'B': 'b' };
params = querystring.stringify(params); // changing into querystring eg 'A=a&B=b'
request.post({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // important to interect with PHP
url: link,
body: params,
}, function(error, response, body){
console.log(body);
});
I highly recommend axios https://www.npmjs.com/package/axios install it with npm or yarn
const axios = require('axios');
axios.get('http://your_server/your_script.php')
.then( response => {
console.log('Respuesta', response.data);
})
.catch( response => {
console.log('Error', response);
})
.finally( () => {
console.log('Finalmente...');
});

Resources