How do I set Authorization Bearer header with nodejs - node.js

I am working on a signup page and I am lost trying to set the Authorization Bearer Header. I am using jsonwebtokens to generate the token. I know how to set the header on postman, but how do I set it for the actual route I’m signing up to and be able to use it in my auth middleware for other endpoints ? As postman is just for tests

request.setHeader('Authorization', 'Bearer '+accessToken)

you can set headers inside request in your route. Using request module.
app.post('/test', (req, res, next) => {
console.log("inside the test");
request.post({
url: api_address,
body: JSON.stringify(send),
headers: {
"Content-Type":"application/json",
"Authorization": "Bearer 71D50F9987529"
}
}, function (error, response, body) {
console.log("hiii");
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results) // View Results
}
});
});

Related

Calling external api from node js with multipart/form-data

Iam using request() in node js to call external apis.
if (req.method == 'GET')
options.qs = req.query;
else
options.form = req.body;
request(options, function(error, response, body) {
if (error || [constants.response_codes.success, constants.response_codes.internal_server_error, constants.response_codes.error, constants.response_codes.unauthorized].indexOf(response.statusCode) < 0) return next(true);
return next(null, { statuscode: response.statusCode, data: response.body });
});
It is working with req.method GET,POST,PUT and DELETE.But I need to send multipart/form-data for sending files from the client side to laravel project via node js.Iam using body-parser in node js for parsing the request.How can it be achieved by using request() in node js to send file.
You can try this
const options = {
method: "POST",
url: "Your URL",
port: 443,
headers: {
"Authorization": "Basic " + auth,
"Content-Type": "multipart/form-data"
},
formData : {
"image" : fs.createReadStream("./images/src.png")
}
};
request(options, function (err, res, body) {
if(err) console.log(err);
console.log(body);
});

Communication between servers using Express and Request

Following scenario:
I got two servers, one server a Website, the other manages a database. The Website sends requests to its server, the request is passed to the backend server and a data set from the database should be returned.
I am using Express on both servers, the one serving the website also has the Request package.
Code on first server:
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:8081/getDataset',
body: "data="+data
},
function(error, response, body){
if (!error && response.statusCode == 200) {
console.log(body)
res.send(body)
}
}
)
Code on second server:
getFromEigenschaft (req, res) {
var data = req.body.data
console.log(req.body) //logs {}
//do database stuff with data
return res.status(200).send(dataSet)
}
On the second server req.body is an empty object though. What am I doing wrong?
Found the answer:
The body object can be set to a JSON, just as I want to, but the JSON option must be set to true:
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:8081/getDataset',
json: true,
body: data
},
function(error, response, body){
if (!error && response.statusCode == 200) {
console.log(body)
res.send(body)
}
}
)

How to pass the information from function in the Express get API in MEAN Stack

Here I have a function hsResponse which is as below and in the console.log I am getting the proper body response when I run this standalone, but now I wanted call inside the app.get() method and I wanted to put the response of hsResponse to the app.get() API response.
After running the API I wanted to get the body (the value which is printed in the console.log) of hsResponse instead of Root API.
How can I achieve this?
var hsResponse = request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
console.log(body);
});
app.get('', (req, res) => {
res.send('Root API');
});
Why not use a function with a callback passed in parameter to handle the request result:
var hsResponse = function (done) {
// done is a function, it will be called when the request finished
request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
if (error) return done(error);
done(null, body);
});
}
app.get('', (req, res) => {
hsResponse( function (err, body) {
if (err) throw err;
// get body here
res.send('Root API');
} );
});
Edit the code above buffers up the entire api response into memory (body) for every request before writing the result back to clients, and it could start eating a lot of memory if there were many requests at the same time. Streams, by using streams we could read one chunk at a time from the api response, store it into memory and send it back to the client:
app.get('', (req, res) => {
request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}).pipe(res);
});
Reference: stream handbook
You can just put the code inside:
app.get('', (req, res) => {
var hsResponse = request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
res.send(body); //<-- send hsResponse response body back to your API consumer
});
});

Wordpress API with Express and NODEJS

Is it possible to make an external http get request from Wordpress API using express?
Let's say I want to make a get request to http://demo.wp-api.org/wp-json/wp/v2/posts - This are a list of posts from wordpress.
Sample:
router.get('/posts', function(req, res){
I should make an external http get request here from wordpress api
("http://demo.wp-api.org/wp-json/wp/v2/posts")
Then I want to display the response as json
}
Update (I figure it out):
I use the request module, so to anyone whose having trouble with it. You can call this function inside your controller:
var express = require("express");
var request = require("request");
var router = express;
var getWPPost = function(req, res){
var headers, options;
// Set the headers
headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
// Configure the request
options = {
url: 'http://demo.wp-api.org/wp-json/wp/v2/posts/1',
method: 'GET',
headers: headers
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send({
success: true,
message: "Successfully fetched a list of post",
posts: JSON.parse(body)
});
} else {
console.log(error);
}
});
};
router.get('/post', function(req, res){
getWPPost(req, res);
}

Node js Request - Empty body in response

I am using node js request to retrieve the HTML from the following URL but the body is returning empty.
var request = require("request");
var url = 'http://www.topshop.com/en/tsuk/product/bags-accessories-1702216/scarves-465/feather-wings-5884878?bi=0&ps=20';
request({
uri: url
}, function (error, response, body) {
console.log(body);
if (response.statusCode != '200') {
console.log('fail');
console.log(response.statusCode + ' # ' + error);
} else {
console.log(response.statusCode);
console.log('############');
console.log(response);
}
});
On closer inspection I can see this in the response:
_header: 'GET /webapp/wcs/stores/servlet/CatalogNavigationSearchResultCmd?langId=-1&storeId=12556&catalogId=33057&beginIndex=1&viewAllFlag=false&pageSize=20&searchTermScope=3&searchTermOperator=LIKE&searchType=ALL&sort_field=Relevance&searchTerm=TS19M11KRED&x=25&y=11&geoip=search HTTP/1.1\r\nreferer: http://www.topshop.com/en/tsuk/product/bags-accessories-1702216/scarves-465/feather-wings-5884878?bi=0&ps=20&geoip=prod\r\nhost: www.topshop.com\r\nConnection: close\r\n\r\n',
_headers:
{ referer: 'http://www.topshop.com/en/tsuk/product/bags-accessories-1702216/scarves-465/feather-wings-5884878?bi=0&ps=20&geoip=prod',
host: 'www.topshop.com' },
Which I assume means that there has been a redirect? Even though its returned a 200 OK instead of a 302 redirect.
I'm not sure of the best way to retrieve the body from the redirect? Do I need to make another request to the URL in the header? But shouldn't the response code be a 302 in this case instead of a 200?
Any help appreciated.
What you show seem like something that happened after a redirect - see that the referer is set to your original URL.
Maybe you should set more headers, like User-Agent because some servers don't respond without it.
For example, see the code that I wrote for this answer:
'use strict';
var request = require('request');
var url = 'https://api.github.com/users/rsp';
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.html_url);
}
});
It returns:
https://github.com/rsp
Note that it doesn't work without the User-Agent header:
'use strict';
var request = require('request');
var url = 'https://api.github.com/users/rsp';
request.get({
url: url,
json: true,
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.html_url);
}
});
It returns:
Status: 403
The same URL, the same code - the only difference is the User-Agent header.

Resources