Reputation: 129
I am new to node.js and JavaScript in general, but I'm trying to use node.js as a simple REST API. A client request comes to node.js, then node.js reaches out to a database to perform crud operations and returns the response back. However, I would like to be able to parse this response and format it in my own JSON before sending back to the client. Right now im using the request library and .pipe()
to send back. Can I .pipe()
into a variable that I could then parse or do I need to change my approach entirely?
Here is what my code looks like at the current moment:
const request = require('request');
var username = "admin";
var password = "admin";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.getPosts = (req, res, next) => {
request({
uri: 'http://localhost:8000/LATEST/search?q=caesar',
headers: {"Accept": "application/json",
"Authorization": auth
}
}).pipe(res);
};
I am aware that request
has been deprecated so maybe there is a better way to do this currently. I appreciate any help and feedback as I'm new to this.
Upvotes: 0
Views: 6837
Reputation: 12542
You can use request
module or axios
or anything. You can just save the JSON body and process it and sent it to the client. Below is how to do it.
const request = require('request');
var username = "admin";
var password = "admin";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.getPosts = (req, res, next) => {
request({
uri: 'http://localhost:8000/LATEST/search?q=caesar',
headers: {
"Accept": "application/json",
"Authorization": auth
}
// You can set json:true here so that you don't have to do JSON.parse below.
}, (err, response, body)=>{
//body is the json body
const jsonBody = JSON.parse(body);
//do something with json request
res.json(jsonBody);
})
};
Upvotes: 1