Node and Express – Conditionally Displaying Pages - node.js

What I want to do seems elementary; but, I am running into some blocks.
All I want to do is display pages based on a condition.
var express = require("express");
var app = express();
app.get('/', function(req, res) {
if (userIsLoggedIn()) {
res.sendFile(__dirname + '/public/index.html');
} else {
res.sendFile(__dirname + '/public/accessDenied.html');
}
});
I am looking to grab information from the browser – I want to call a function from another browserify-ed file, and use the return value to determine which page is displayed to the user.
I can't run the server from app.js because it needs to be browserify-ed since it requires Web3. And since the function relies on state, I am not sure how to access this state from the server file.

You have to post data from the browser to the server either with a form or query parameter.
For example:
web3.shh.post(object [, callback])
https://web3js.readthedocs.io/en/1.0/web3-shh.html#post
on the server site you need to extract those values and have to reply based on your posting.
How to process POST data in Node.js?
Unfortunately your use case is not clear ,but in general you might want to check out how to handle HTTP API communication.

Related

Is all communication from frontend to backend done via routes?

I'm working on a vuejs/express fullstack web app, and I know you can specify endpoints on the server like:
app.get('/', function (req, res) {
res.send('GET request to the homepage')
})
Which you can then hit from the client to display the home page.
But I'm wondering what about when you don't need to go to a 'route'? For example, you just want to send some data from client to server to do some calculations and then send data back to the client - do you still specify an endpoint e.g /FunctionName and access it from the frontend in the same way or is there some other way to call a function in the backend?
This is the 'express' way to define endpoints (or routes), regardless if it will return an html page like the example you've specified, or do some computation by calling other functions with user-specified parameters.
As a basic example:
app.post('/myendpoint', function (req, res) {
returnValues = callMyFunction(req)
res.send(returnValues)
})

How to get url of a page that makes a http ajax GET request in node.js?

In node.js I have a site that serves pages from the same server. Pages can request for files on the same server using http get with ajax. However some pages are not allowed to request a file from a certain path. How can I validate this in node.js?
Also this should be in a way a user can't hack from client side. The node.js would need a way to see if the request came from a page from a certain url and if so then block it if the link it requests is in a specified folder.
Thanks
Assuming you've setup your server like so:
var http = require('http');
server = http.createServer(function(req, res)
{
...
you can get the referring URL by accessing req.headers.referer
Then you'll need to check this either with a regular expression (if the allowed URLs match a pattern) or against an array of acceptable values.
UPDATE
Next, you could keep an array of valid visited URLs in a session and then check if the acceptable referring URL is actually in this list (and thus not necessarily spoofed).
In any node function , we have access to request and response object. Consider the following eg :
var express = require('express');
var router = express.Router();
var app = express();
app.get('/', function(request, response){
var urlPath = request.path;
response.send("Hello");
});
app.listen(3000);

configure NodeJS process on two different machine

I have two different nodejs web app running on two different machine.
But I need to have one endpoint to user api1.abc.com/v1 to go one process and api2.abc.com/v2 go to another process.
how can i do this kind of request with the single endpoint to user (abc.com). need a nginx setup guide ?
I need this setup because internally I need to call user authenticated api from one server to another.
On one server you need to receive the data (using express & router):
router.get('/v1', function(req, res) {
// TODO
res.render('something');
});
and on the other you need to fetch:
var express = require('express');
var router = express.Router();
var app = express()
app.use('api1.abc.com', router);
router.post('/v1', function(req, res) {
// process res
});
You can write code at version two apis. In request you can pass version on which you need to call.
Call all api's on version 2. If it required to call on second server. Write code on version one to identify the call from version 2. So that it can by pass the basic authentication.
Thanks,

Correct way to route with node js and socket.io

Currently I have a node JS application that requires both realtime data and an archive of past data. I have a script running that sends the data through a socket.io to my front end interface. I grab all of my data from a mongodb database on the socket connect method but this is a waste since I only want some data on one page and other data on another page.
app.get('/', function(request, response) {
response.sendfile(__dirname + "/index.html");
});
Should I be placing my socket connection inside this app.get function or is there another way? I want to make sure that I only grab that data I need from a mongoDB for the page that is being requested rather then getting all the data and parsing it on the front end.
I used the url.parse function to get the name of the page like so:
var curURL = url.parse(request.url).pathname;
Then I can check the current URL
if (curURL == '/') {
//code
}

Node.js redirect to another node.js file

I want to do a re-direction from one nodejs file to another nodejs file. I used res.redirect(URL), but when execute it says "cannot GET /nodepage"
Currently I am using
// Handler for GET /
app.get('/nodepostgres', function(req, res){
res.redirect('/nodepost.js?a=1');
});
I think there are a few things that you don't explain properly or don't understand properly in your question.
I am not sure what you mean about "re-direction from one nodejs file to another nodejs file". You seems to think that a node script file correspond to a URL (or a page). That's wrong. A node script correspond to an application that may (or may not) expose several pages through several URL and can imports application logic from other script files (you will run a single root script file for a site or application). It's totally different from what you may know with (vannilla, no framework) PHP.
Exposing different pages through different url is called Routing, all Express documentation about routing can be found here.
What I understand is that your trying to make a function / page / Url per script : nodepost.js file is a page. Code organization is a good thing but let's focus on how node + express works first.
From what I understand, you're applicaton has a few exposed url, let's say :
"/" homepage
"/nodepostgre" (maybe accepting an 'a' arg ?)
"/nodepost" accepting an arg : a
Note : we forget the id of file = page, we don't want an extension to appear on URL so nodepost.js becomes nodepost
What you can do is setup the 3 url expositions :
app.get('/', function(req, res) { res.render('home'); }); // render the home page
app.get('/nodepost', function(req, res) { // expose the nodepost function
var a = req.params.a;
doSomethingWith(a);
// res.render, res.send ? whatever you want...
]);
app.get('/nodepostgres', function(req, res){ // use of res.redirect(url[, status])
res.redirect('/nodepost');
});
Is that what you want ?
Then, here is a more elegant way to handle params ("a").
app.get('/notepost/:a', function(req, res) { // called via /nodepost/here_goes_a_valu ; no "?"
var a = req.params.a;
});
Why is it better ?
Respect REST (may not be the best link to describe rest but...)
Allows you to expose '/nodepost' without params
Certainly one million other things

Resources