How to add headers in superagent GET request - node.js

Here is a basic code:
const superagent = require('superagent');
superagent.get('https://api.arabam.com/pp/step')
.query({ apikey: '_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA==' })
.end((err, res) => {
if (err) { return console.log(err); }
console.log(res.body.url);
console.log(res.body.explanation);
});
But apikey is header rather than query. How do I send it as a header?
Edit:
I have tried using request module and it simply says that I'm unable to access it
var request = require("request");
request({
uri: "https://api.arabam.com/pp/step",
method: "GET",
'Content-Type' : "application/json",
apikey: "_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA=="
}, function(error, response, body) {
console.log(body);
});
It says unauthorized to access

From the Setting header fields doc, you should use
request.set('apikey', '_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA==')
to set the header field.

Related

Request succeeds with `request` but fails with `axios`

I have this microsoft graph authentication code, making what I think is the same request using axios and then using request. However, the axios request fails with 404, whereas the request request succeeds. What am I doing wrong with axios?
const axios = require('axios')
const request = require("request");
const FormData = require('form-data');
const data = FormData()
data.append('client_id', XXXXXXXXXXX),
data.append('client_secret', XXXXXXXXX),
data.append('scope', "https://graph.microsoft.com/.default"),
data.append('grant_type', 'client_credentials')
const requestParams = {
client_id: logins.activedirectory.clientID,
client_secret: logins.activedirectory.clientSecret,
scope: "https://graph.microsoft.com/.default",
grant_type: "client_credentials",
};
const endpoint = "https://login.microsoftonline.com/" + XXXXXXXX + "/oauth2/v2.0/token";
///////// AXIOS //////////
axios({
method: 'post',
url: endpoint,
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
///////// REQUEST /////////
request.post({ url:endpoint, form: requestParams }, function (err, response, body) {
if (err) {
console.log(err);
} else {
console.log(body);
}
});

nodejs request post large json fail

I am trying to post large json to a http server(a grafana server actually):
here is my code:
const http = require('http')
const request = require('request')
const fs = require('fs')
const opts = {
hostname: 'myip',
port: 3000,
path: '/api/dashboards/uid/KPEiIQVWk',
method: 'GET',
timeout: 5000,
headers : {
'Authorization' : 'Bearer ********************************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
}
const req = http.request(opts, res => {
console.log(`Fetch: statusCode: ${res.statusCode}`)
var origin = ''
res.on('data', d => {
origin += d
})
res.on('end', function(){
dash = JSON.parse(origin)
dash.dashboard.panels.forEach(p => {
if(p.id == 26){
fs.readFile(__dirname + '/grafana/pm/branch-graph.html','utf-8', function(err, newPanel){
if(err){
console.log(err)
}
p.content = newPanel
const fresh = JSON.stringify(dash)
const updateOptions = {
uri: 'http://myip:3000/api/dashboards/db',
method: 'post',
headers : {
'Authorization' : 'Bearer *************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Content-length' : fresh.length
},
json: fresh
}
fs.writeFile('tmp.json', fresh, function(err){
if(err){
console.error(err)
}
})
request(updateOptions, function(error, response, body){
console.log(`update: statusCode=${response.statusCode}`)
console.log(`update: ${body}`)
})
})
}
})
})
})
req.on('error', error => {
console.error(error)
})
req.on('timeout', () => {
req.abort()
})
req.end()
as you can see, I first fetch a grafana dashboard's source, then make some udpate, then post it back to grafana server. but always get 400 error. The strange thing is that if I dump the json to a file and use curl to post, it will work.
curl -vH "Authorization: Bearer $TOKEN" -H "Expect:" -d #tmp.json -H "Content-Type:application/json" http://myip:3000/api/dashboards/db
the whole json is about 40000+ bytes. any hint on this? I am not very famillar with nodejs. I am just trying to write some CI scripts.
First, I don't think it's necessary to use both the http and request modules. http is a module built into nodejs, and request is an npm package.
I recommend you use the npm request package because it's easier. You can read its documentation here: https://www.npmjs.com/package/request#http-authentication
Second, the options you're passing to the request module is not formatted correctly, I think this is why it is not working. With your current code, I would console.log('POST error', error); to print out the error. The correct options for the request module is proposed below.
const options = {
url: 'https://myip:3000/api/dashboards/db',
body: fresh, // the json from the fs.read callback
auth: {
'bearer': 'bearerToken'
},
json: true // from docs: If json is true, then body must be a JSON-serializable object.
}
request.post(
options,
(err, httpResponse, body) => {
console.log(err, body);
});

Why i am getting unable to open document error or blank pdf in opening a pdf on client side?

I am hitting a get api in react similar to http://www.orimi.com/pdf-test.pdf which needs some secret information which is available only at middleware written in node. I want to open the pdf on client side(browser). So I am hitting the proxy get api which will hit the middleware and middleware will hit the backend server, but I am getting unable to open document and blank pdf. Can anyone tell me what is wrong with this code?
fetch(pdfApiMiddlewareUrl, {
method: "GET",
headers: {
"Content-Type": "application/pdf",
'Content-Disposition': 'inline; filename=your_file_name'
},
responseType : 'blob'
})
.then(res => res.blob())
.then(response => {
var blobUrl = URL.createObjectURL(response);
window.open(blobUrl);
})
.catch(error => {
console.log("HEREEEEEEEE");
console.log(error);
});
MIDDLEWARE CODE:
var urlEndPointsToHit = decodeURIComponent(req.query.urlToHit);
var url = urlEndPointsToHit+'?secret='+secretInfo;
var options;
options = {
url: url,
method: 'GET',
headers: {
'Content-type': 'application/pdf'
},
};
if(options) {
options.qs = req.query || {};
}
request(options, function(err, resp, body) {
req.locals = body;
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Cache-Control', 'no-cache');
next();
});

How to properly use putAsync

I searched here and there and ended up with no finding regarding putAsync method of promisified request by bluebird.
var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));
request.putAsync({
uri: buApiUrl,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
name: BU,
workstations: formattedWorkStaions[BU]
})
}).spread(function (response, body) {
debugHelper.log(body);
}).catch(function (err) {
debugHelper.error(err);
});
Above is the code snippet that is in my program. And it does not send put request. While using postAsync, if will send post request successfully.
Your code seems fine to me.
Example
var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));
request.putAsync({
uri: 'https://httpbin.org/put',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
name: 'anon'
})
}).spread(function (response, body) {
console.log(body);
}).catch(function (err) {
console.error(err);
});
OR you can just pass JSON body like this -
request.putAsync({
uri: 'https://httpbin.org/put',
json: { name: 'anon' }
})
....
Make sure the API end-point is taking PUT requests and the variables BU,formattedWorkStaions[BU] are properly defined. I guess formattedWorkStaions should be formattedWorkStations?

use GET method in node js request?

i want to pass data with GET method in node js , my response is ok but in php file $_GET is empty. what is wrong?
var querystring = require('querystring');
var req = require('request');
var form = {
number: 'test',
msg: 'test',
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
req({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://localhost:8080/sms/index.php',
body: formData,
method: 'GET'
}, function (err, res, body) {
console.log('res is',res);
console.log('err',err);
});
An HTTP GET request cannot have a request body. $_GET parses parameters from the query string. The headers Content-Lengthand Content-Type do not make sense for a GET request as they apply to the body of the request, which GET cannot have. You need to use the qs option instead of body.
req({
uri: 'http://localhost:8080/sms/index.php',
qs: form,
method: 'GET'
}, function (err, res, body) {
//
});

Resources