Is there anyway to stored res.send() into variable - node.js

How can store a json result of res.send() in express js into a variable so that we can archive result without display it into html page?
this.app.post('/profile', (req, res, next) => {
let a = somefunction();
res.status(200).send(a);
});

How can store a json result of res.send() in express js into a variable
Just assign it to a variable like usual:
const myResObject = res.status(200).send(a);
(...) without display it into html page?
Not possible. You have no control over what res does internally without monkey patching the prototype.
You can modify your view to not display anything at all when res.send is called.

Related

Pass URL as query parameter in node js

I am trying to hit the URL http://localhost:3000/analyze/imageurl=https://www.google.com/ from my browser.
However, due to the presence of //, it does not correctly hit the URL, and gives me an error message, Cannot GET /analyze/imageurl=https://www.google.com/
If I get rid of the backquotes as follows, http://localhost:3000/analyze/imageurl=httpswww.google.com/, it does work correctly.
My backend API looks like this
app.get('/analyze/:imageurl', function (req, res) {
console.log('printing image url:' + req.params.imageurl);
}
Is there a way I can pass in the imageurl with backquotes as a query parameter?
You need to encode your URL before pass it on query string, using encodeURIComponent. For example:
var urlParam = encodeURIComponent('https://www.google.com/');
console.log(urlParam); // https%3A%2F%2Fwww.google.com%2F
var url = 'http://localhost:3000/analyze/' + urlParam;
console.log(url); // http://localhost:3000/analyze/https%3A%2F%2Fwww.google.com%2F
// Decode it in API handler
console.log(decodeURIComponent(urlParam)); // https://www.google.com/
encodeURIComponent
One approach could be to use Express' req.query in your route. It would look something like this:
// Client makes a request to server
fetch('http://localhost:3000/analyze?imageurl=https://google.com')
// You are able to receive the value of specified parameter
// from req.query.<your_parameter>
app.get('/analyze', (req, res, next) => {
res.json(req.query.imageurl)
})

Return view and send data to react after passport.js oauth

First let me say that sorry if this is a simple question, I'm new to react and express and couldn't find the answer on SO.
I'm trying to pass data to a react object as well as render a view based off of a passport.js return route.
I have the object i need to pass I just can't figure out how to pass it.
First the user hits the auth route
router.get('/steam',
passport.authenticate('steam'),
(req, res) => {
//Not used
});
Then after they login through steam they're returned to this route:
router.get('/steam/return',
passport.authenticate('steam', { failureRedirect: '/' }),
(req, res) => {
res.redirect('/dashboard');
});
From here I'm passing them to the /dashboard route where im taking the user object and creating another call to grab their library and then sending the data to the view:
router.get('/', (req, res, next) => {
var OwnedGamesReqUri = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=' + process.env.STEAM_API + '&steamid=' + req.user.steamid + '&format=json&include_appinfo=1';
request(OwnedGamesReqUri, (error, response, body) => {
if (!error && response.statusCode == 200) {
var resObj = JSON.parse(body);
//name, playtime_forever, playtime_2weeks, img_icon_url, img_logo_url
res.render('dashboard', { user: req.user, games: resObj.response.games});
}
});
});
I'm able to grab all of the data I need in the dashboard view via handlebars but the problem I'm facing is what I can do to pass the ownedgames data to a react object in another JS file. I have a react component set up in another file that is loaded to the dashboard via a bundle file. I'm assuming this needs to go to the server but I'm just not exactly sure how to achieve this.
Your question isn't about reactjs or passportjs. It's basically how we can pass a variable in server-side javascript to client-side javascript. So you can use that variable in whatever the framework you use in the client-side.
The simplest way to achieve this is rendering your value as variable declaration within an inline script tag in your template. So your client js will have a global variable with that value, which can access from anywhere in your client side scripts.
As an example, if have a variable with string value as follows
var test = 'abc';
You can render it in your template as a variable declaration within a script tag.
res.render('template', test)
template file:
<script>
var test = '{{test}}';
</script>
Now this template will generate an HTML page as follows.
<script>
var test = 'abc';
</script>
So test variable will be a global client side javascript variable with value 'abc', which can access from any other javascript code on the same page.
Even though this is simple as above for a string variable, things get complicated when you are trying to send an object. Because object variables render in the template as [Object object]. To avoid this, you need to send stringify version of your object before sending it the handlebar template.
var data = JSON.stringify({ user: req.user, games: resObj.response.games});
res.render('dashboard', data);
Then your dashboard template needs to have script tag with the variable declaration in addition to its original content.
//...
<script>
var data = {{data}};
</script>
//...
Now, data will be a global variable in your client side and you can use it in your reactjs code to access user and games.
There are several ways to do this, depending on how your React component manages its state.
Reactive state (RxJS, mobx, nx-observe):
The easiest to deal with, your component as well as the non-js code can both access these stores and catch up on the updates together. This provides a very loose coupling between the data provider and consumer.
Component with a flux pattern:
If your component is using Redux, Reflux or any other flux based library to manage state, you can export corresponding actions/functions from your flux code which any JavaScript code can call to update your component's state.
State maintained within the component:
Somewhat messy. In this case your component can export a callback which your script can call to send it new data.

iterative render with node and express

New to node and async and still struggling with concepts.
Trying to use express/handlebars render with a callback to iteratively build an html body with content from an array. End goal is to send a response with a number of emails each one individually rendered using a view.hbs.
Got this far but realised it was never going to work. res.render can't pass my html variable back in the callback and res.send would run before the renders have completed???
function buildRes (req, res, email) {
var html = '';
Object.keys(email).forEach(function (i) {
res.render('emailPanel', {subject: email[i].subject, body: email[i].body},
function(err, renOut) {
if err throw err;
html=html+renOut;
}
)
})
res.send(html);
}
Any suggestions on how I should be approaching this problem?
Started out trying to use handlebars #each helper to do the iteration but all of the examples show a simple list whereas in my case there a multiple array parameters to be passed to the render.
I'm still not sure what you're trying to accomplish with this, but one is for sure, I think it's better for you to do all looping inside your view by passing the entire array (filtered) with res.render to your view. Also note that you can respond only once per request.

How to pass selected data from database to view file in Node js?

I am trying to pass selected data from database in Node Js. But i could not able to pass the data to view. Is there any proper way to pass data and display into view in Node Js.
try
app.get('/',function(req, res){
var data = fetchFromDataBase();
res.render('viewName',{data: data});
});
in viewName (assuming data is string) do
block content
p content is #{data}
hope it helps :)
Alternative Solution:
You can pass the data by setting on res.locals to the view as below:
function(req,res,next){
res.locals = {
data : fetchDataFromDatabase() // some function
};
res.render('view');
}
in view you can access it directly using:
data
e.g. in Jade:
html
head
title helloWorld
body
h1 #{data}
Explain:
This object contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any).
res.locals is an object passed to whatever rendering engine your app is using (in this case jade). It is 'global' in the render, so you don't need to prepend anything on to them to use them.

How to get req and res object of Expreejs in .ejs file

I am trying to use Express js with .ejs views.
I want to redirect my page to some another page on any event let say "onCancelEvent"
As per Express js documentation,I can do this by using res.redirect("/home");
But I am not able to get res object in my ejs file.
Can anyone Please tell me how to access req and res object in .ejs file
Please help.
Thanks
Short Answer
If you want to access the "req/res" in the EJS templates, you can either pass the req/res object to the res.render() in your controller function (the middleware specific for this request):
res.render(viewName, { req : req, res : res /* other models */};
Or set the res.locals in some middleware serving all the requests (including this one):
res.locals.req = req;
res.locals.res = res;
Then you will be able to access the "req/res" in EJS:
<% res.redirect("http://www.stackoverflow.com"); %>
Further Discussion
However, do you really want to use res in the view template to redirect?
If the event initiates some request to the server side, it should go through the controller before the view. So you must be able to detect the condition and send redirect within the controller.
If the event only occurs at client side (browser side) without sending request to server, the redirect can be done by the client side javascript:
window.location = "http://www.stackoverflow.com";
In my opinion: You don't.
It is better to create the logic that determines the need to redirect inside some middleware that happens long before you call res.render()
It is my argument that your EJS file should contain as little logic as possible. Loops and conditionals are ok as long as they are limited. But all other logic should be placed in middleware.
function myFn( req, res, next) {
// Redirect if something has happened
if (something) {
res.redirect('someurl');
}
// Otherwise move on to the next middleware
next();
}
Or:
function myFn( req, res, next) {
var options = {
// Fill this in with your needed options
};
// Redirect if something has happened
if (something) {
res.redirect('someurl');
} else {
// Otherwise render the page
res.render('myPage', options);
}
}

Resources