How to always add prefix to url in Node.js request - node.js

I'm using the package "request" (https://www.npmjs.com/package/request) in Node.js. What I want to have is somehow like the "defaults" api, that I give a default url prefix to the request object, the url of any request which sent from my request object will be prefixed before sending. Is that possible? Thank you!

You can use request.defaults
const request = require('request');
const baseRequest = request.defaults({baseUrl : 'https://example.com/api/'}})
now use baseRequest object
Documentation Link-
Request.defaults

You can create a default request instance, in there config you baseUrl
var request = require('request');
var r = request.defaults({
baseUrl: 'https://example.com/api/',
})
r({
'url':'/end/point?test=true',
'method': "GET",
},function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}); // will fetch https://example.com/api/end/point?test=true

Related

Pass post data to another url and get url response in post response

I am trying to pass some data to /card then filter it and send to a url and the final response of my /card need to be response send from the url.
app.post('/card', (req, res) => {
var testData = req.body.orderId;
if(testData!=null){
var options = {
uri: 'https://localhost',
headers: {'content-type' : 'application/json'},
method: 'POST',
json: {"longUrl": testData}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// res.json(testData);
console.log(body.id) // Print the shortened url.
}
});
}
});
You can use Node.js core module http to make an http request from within your Node application.
You can consult the official documentation and various options here https://nodejs.org/api/http.html#http_http_request_options_callback

Node.JS make multiple POST requests untill response is empty

I'm making a POST request to API that has limited number of characters in response. In order to get full response I need to make multiple POST requests and then append them all to one file. I'm not that familiar with asynchronous programming so I can't think of a solution for my problem. Here is snippet of my code:
var request = require('request');
var fs = require('fs');
var options = {//options for POST request body};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
fs.appendFileSync("./response.json", JSON.stringify(body), 'utf8');
var resp = JSON.parse(fs.readFileSync('./response.json', 'utf8'));
options.offset = resp.parameters.length; //this is length of my data so far, next request will have this number in it and response will be new data offseted by this number
}
});
And after this request I need to make another one untill body.length is zero. So I guess what I need is to call request function from its own callback. How do I achieve this? Thanks!
Like JM-AGMS said, wrap the request function call in another function to have the callback of one request trigger the next request.
A recursive solution would look somewhat like this:
var request = require('request');
var fs = require('fs');
var options = {/*options for POST request body*/};
function loop(options) {
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
if (body.length !== 0) {
fs.appendFileSync("./response.json", JSON.stringify(body), 'utf8');
var resp = JSON.parse(fs.readFileSync('./response.json', 'utf8'));
loop({ ...options, offset: resp.parameters.length });
}
}
});
}

Consuming a service API using nodejs + jsonwebtoken(jwt)

Hello guys i want to use node.js to retrieve the user authenticated from an api URL.
I retrieved the codeToken(jsonwebtoken) and put it in the header of my request in postman it works.
But when i go to the code i can't find a way to use node.js+express request, to retrieve the json response of the user that's logged in using all that.
i can't put the url of the API in the sake of the client.
here is my code guys but it's not the right one please advise
var request = require('request');
var options = {
url: '**********',//for the sake of client hidden
headers: {
tokenCode: '15288648455b20a04d5463e'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info);
}else
//console.log(response );
console.log(response.statusCode);
}
request(options, callback);
Headers in my POSTMAN (only tokenCode)

Insert data through SPARQL over HTTP POST request from node js

I am using 'request' module in my node app to POST data in ontology model which resides in a fuseki server. I am using the following code:
var request = require('request');
var querystring = require('querystring');
var myquery = querystring.stringify({update: "PREFIX test:<http://www.semanticweb.org/muhammad/ontologies/2017/2/untitled-ontology-14#> INSERT { ?KPIs test:hasValue 2009} WHERE { ?KPIs test:hasValue ?Newvalue}"});
request.post('http://localhost:3030/DS-1/sparql?'+myquery, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Show the HTML for the Google homepage.
console.log('successful update');
console.log(body);
} else {
console.log(response.statusCode);
console.warn(error);
}
});
PS: When I use POSTMAN to send the Post request to insert data it works fine but from my node app, it doesn't. it shows error 'bad request 400'.
P.S: GET methods work fine from both POSTMAN and node app.
Problem Solved:
I was making mistake in the format of post request. The corrected format is given below.
var request = require('request');
var querystring = require('querystring');
var myquery2 = querystring.stringify({update: "PREFIX test:<http://www.semanticweb.org/muhammad/ontologies/2017/2/untitled-ontology-14#> INSERT { ?KPI_Variables test:hasValue_ROB1 2000} WHERE { ?KPI_Variables test:hasValue_ROB1 ?Newvalue FILTER(?KPI_Variables= test:Actual_Production_Time)}"});
request.post({headers: {'content-type' : 'application/x-www-form-urlencoded'},url:'http://localhost:3030/DS-1/?'+myquery2 }, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Show the HTML for the Google homepage.
console.log('successful update');
console.log(body);
}
else
{
console.log(response.statusCode)
console.warn(error);
}
});
I was missing the 'headers' and 'url' elements in my request.post.
/DS-1/sparql is the query service.
INSERT is an update operation.
Try /DS-1/update
It is better to POST the update in the body of the request with a Content-type. ?update= may not work.

Encoding issue with requesting JSON from StackOverflow API

I can't figure this out for the life of me. Below is an implementation with the request module, but I've also tried with the node-XMLHttpRequest module to no avail.
var request = require('request');
var url = 'http://api.stackexchange.com/2.1/questions?pagesize=100&fromdate=1356998400&todate=1359676800&order=desc&min=0&sort=votes&tagged=javascript&site=stackoverflow';
request.get({ url: url }, function(error, response, body) {
if (error || response.statusCode !== 200) {
console.log('There was a problem with the request');
return;
}
console.log(body); // outputs gibberish characters like �
console.log(body.toString()); // also outputs gibberish
});
Seems to be an encoding issue, but I've used the exact same code (with native XHR objects) in the browser and it works without problems. What am I doing wrong?
The content is gzipped. You can use request and zlib to decompress a streamed response from the API:
var request = require('request')
,zlib = require('zlib');
var url = 'http://api.stackexchange.com/2.1/questions?pagesize=100&fromdate=1356998400&todate=1359676800&order=desc&min=0&sort=votes&tagged=javascript&site=stackoverflow';
request({ url: url, headers: {'accept-encoding': 'gzip'}})
.pipe(zlib.createGunzip())
.pipe(process.stdout); // not gibberish
Further Reading: Easy HTTP requests with gzip/deflate compression
While pero's answer is correct, there's a simpler way to do this.
Since you're using request, you can also just add the gzip: true flag:
var request = require('request');
var url = 'http://api.stackexchange.com/2.1/questions?pagesize=100&fromdate=1356998400&todate=1359676800&order=desc&min=0&sort=votes&tagged=javascript&site=stackoverflow';
request.get({ url: url, headers: {'accept-encoding': 'gzip'}, gzip: true }, function(error, response, body) {
console.log(body); // not gibberish
});

Resources