I am tryng to send an array as a param so I have the following code
var myJsonString = JSON.stringify(url);
request.get('http://localhost:8090/saveURL/'+myJsonString, function(req, res,body) {
console.log(body);
})
How I can send params with node ?
EDIT
I changue my request petition , now I am using this.
request.get({
url: 'http://localhost:8090/saveURL/',
qs: { param1: JSON.stringify(url)}
},
function(req, res,body) {
console.log(req);
console.log(body);
}
)
This is correct ?
According the the request docs, you can use qs to pass an object of query params:
request.get({
url: 'http://localhost:8090/saveURL/',
qs: { param1; 'a', param2: 'b'}
},
function(req, res,body) {
console.log(body);
}
)
I'd recommend performing this with POST method and not GET, which is more appropriate for altering data on the server.
Also, the URL length is limited and if your data is very large, it won't work.
For instance:
request.post(
'http://localhost:8090/saveURL/',
{ json: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
Replace { key: 'value' } with a POJO (a normal JS object).
Related
I'm using the request package to send a post request to get an authToken, and then a get request to get an array of parcel objects so I can send it on to the rest of my app. When I log the body.parcels, it shows me several [Object, Object] items. I can't see the data inside of these objects, so I'm having trouble figuring out what the data is.
var options = {
uri: 'https://api.onetracker.app/auth/token',
method: 'POST',
json: {
email: this.config.username,
password: this.config.password,
},
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
const authToken = body.session.token;
const options = {
uri: 'https://api.onetracker.app/parcels',
method: 'GET',
json: true,
headers: {
'x-api-token': authToken,
},
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
let result = body.parcels;
console.log('Result: ' + result); // check
this.sendSocketNotification('ONETRACKER_RESULT', result);
}
});
}
You need to change your print line to:
console.log('Result: ', result); // check
See: How can I display a JavaScript object?
I'm trying to develop a currency converter using node.js. I'm using 'request' to make HTTP requests.
Currently in my code, the query strings (q=1, from=USD, to=LKR) are hard coded in the url.
I want to know how to pass those strings as arguments in order to make it dynamic and get as many currency formats as I want.
var request = require('request');
const options = {
url : "https://currency-exchange.p.rapidapi.com/exchange?q=1&from=USD&to=GBP",
headers: {
'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
}
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(response.body);
}
}
request(options, callback);
You can use the qs parameter in the request library when performing a new request.
As specified here https://stackoverflow.com/a/16903926/7088387
You could use this:
const params = {
q: 1,
from: 'USD',
to: 'GBP'
};
const options = {
url : "https://currency-exchange.p.rapidapi.com/exchange",
headers: {
'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
},
qs: params
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(response.body);
}
}
request(options, callback);
You could have a variable that stores those:
var currencies = ['USD', 'GBP'];
And then just put those variable values into your request string:
url : "https://currency-exchange.p.rapidapi.com/exchange?q=1&from=" + currencies[0] + "&to=" + currencies[1]
You could also use template literals using backticks like so:
url : `https://currency-exchange.p.rapidapi.com/exchange?q=1&from=${currencies[0]}&to=${currencies[1]}`
I have this problem, i have been trying 2 days to solve it.
My Javascript code:
const request = require('request');
var req = {
url: 'https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql',
method: 'POST',
headers: { "Content-Type": "application/graphql" },
body: `{
stop(id: "HSL:1122441") {
stoptimesWithoutPatterns(numberOfDepartures: 1) {
realtimeArrival,
scheduledArrival,
realtime,
serviceDay,
headsign,
}
}
}`
};
request(req, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.stringify(JSON.parse(body), null, 4));
}
I want to get the data what the api sends back, into variables or somekind of thing, so i can call them anywhere in the script. The json data what comes back:
{
"data": {
"stop": {
"stoptimesWithoutPatterns": [
{
"realtimeArrival": 60065,
"scheduledArrival": 60000,
"realtime": true,
"serviceDay": 1547676000,
"headsign": "Olympiaterminaali via Kallio"
}
]
}
}
}
but when i use something about like this;
let stoptimesWithoutPatterns = body['stop'].stoptimesWithoutPatterns
it gives me error as
TypeError: Cannot read property 'stoptimesWithoutPatterns' of undefined
As im very new to coding coding, i dont know very tehnical stuff. It would be cool if somebody could help me :) as i wanted to have my own website or app based around this if i can get this to work! Thank you!
By using this i accomplished what i wanted, thank you guys who commented! :) This gives me the value of realtimeArrival! :)
const request = require('request');
var req = {
url: 'https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql',
method: 'POST',
headers: { "Content-Type": "application/graphql" },
body: `{
stop(id: "HSL:1122441") {
stoptimesWithoutPatterns(numberOfDepartures: 1) {
realtimeArrival,
scheduledArrival,
realtime,
serviceDay,
headsign,
}
}
}`
};
request(req, function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(JSON.parse(body));
//console.log(JSON.stringify(JSON.parse(body), null, 4));
let Parsed = JSON.parse(body);
let stoptimesWithoutPatterns = Parsed.data.stop.stoptimesWithoutPatterns[0]['realtimeArrival'];
console.log(stoptimesWithoutPatterns)
}
});
I've learnt dealing with ajax calls to exchange information from the server to the browser but now I'm having big troubles converting my code to a server-side node compatible JS using http requests. I've read different tutorials but I just can't adapt them to my code.
My simple JS / jQuery function is this:
function ajaxCall(data, php, callback) {
ax = $.ajax({
type: "POST",
data: data,
url: php,
success: function (raw_data) {
f = $.parseJSON(raw_data);
callback(f);
},
});
}
And I need to convert it to a pure JS version with http requests to use with node.js. Thanks for any help.
EDIT: I tried and tried, but without success. Here is the code I used, I just get lots of meaningless words on my console.log, perhaps you can correct it:
Version 1
var data = {"action": "update", "tN": 2155};
var request = require("request");
request.post({
url: 'http://example.com/PHP.php',
data: data,
}, function(error, response, body){
console.log(body);
}
);
Version 2
var request = require("request");
var options = {
method: 'POST',
uri: 'http://example.com/PHP.php',
data: {"action": "update", "tN": 2155},
};
request(options, function(error, response, body) {
if(error){
console.log(error);
}else{
console.log(response);
}
});
Use request.js
Example:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
Documentation request.js
I am trying to list all jobs with a certain tag on angel.co using their API with the current call
https://api.angel.co/1/tags/10/startups
and then trying to parse it and show in the browser using restify
var tagUrl = "https://api.angel.co/1/tags/10/startups"
request({
url: tagUrl,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
}
else console.log("error" + error)
})
I'm getting the console.log(body)-part to work, but when I am trying to send the response to the browser it doesn't show anything when I am trying to send it with
res.send('hello ' + req.params.name + body);
Should I parse or stringify it in some way ?
edit: This is the final code
function respond(req, res, next) {
var tag = req.params.tag;
var url = "http://api.angel.co/1/tags/"+tag+"/startups/?
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
res.send( req.params.name + JSON.stringify(body));
}
else console.log("error" + error)
})
Use stringify property of json,which converts the json format to string
JSON.stringify(body)