Run multiple node apps on same server and domain - node.js

I am wanting to split up an application I have into multiple different applications. I want to start with the presentation layer and the logical layer. I want the HTML, CSS and JS all in it's own application but then have the backend code (API) run in it's own application. I don't understand is how to run both on the same server. Currently my overgrown application runs on port 8080 and I use Nginx to do proxy_pass to port 8080 for the / location.
What do I do here?

Maybe you can run multiple instances of node,of course thats need to be a diferent version. Run in diferent ports and match with proxy_pass.
I Might help you.

My suggestion would be to use view engines, such as EJS etc.
In node.js you can send HTML files to the user, so for example when some one visits www.domain.com/register you send him an HTML file, by using something like this:
var path = require('path'); // Core Module in Node JS
res.sendFile( path.join( __dirname, "register.html" ) ); // Send the register HTML file
Although it wouldn't be the cleanest solution, you could also create multiple servers in the code, each using a different port.
Since you want a Front End and a Back End on the same server, you could make one server for the front end on port 80 ( and 443 if you are using SSL ) and another server on a different port, such as 3000, or whatever your heart desires.
You can then get info from the server with Ajax, or something similar, that is entirely up to you.
Here is an example:
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Front End!');
res.end();
}).listen(80);
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Back End!');
res.end();
}).listen(3000);
I would personally always go with the first example, as it is what most people opt for, and it is much easier to implement.
Also, view engines allow you to embed variables from your node.js application into the HTML files, so there won't be any need for Ajax etc.

Related

Simple web page will not run on xbox one edge browser

I am starting to learn html, css, and nodejs, and after writing a couple of very basic web pages I tried to run them on my computer, and view the page on my xbox-one with edge, but for each one (no matter how simple) it always says "Application is not supported, The webpage tried to start an application, such as an email program, that is not supported on xbox". I've tried with using the node html library as well as the express library, with and without html/css.
One code that would not work on the xbox:
server.js
var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("hello world!");
})
var PORT = 1021;
server.listen(PORT);
console.log("Server is running on 192.168.0.15:", PORT, '\n');
I can't find anything online, so any help would be greatly appreciated
Well after a lot of trial and error I found out that it was a very simple problem, I was putting 192.168.0.15:12345 into the address bar but it wanted http://192.168.0.15:1021.

create-react-app with Express

I need to query a database and I'm using create-react-app. The library to connect to the DB (pg-promise) does not work with Webpack and needs to be running on a Node server.
So I installed Express and have this:
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
})
How can I load data from the database from the React pages? I though of using request but how can I make a request to my own server? And what should I add to the lines of code above? I think it would be something like:
app.get('/query/:querybody', (req, res) => {
// process and return query
})
Is this right? How can I make it work with a SPA?
Probably the most friction-free method would be to have a separate app.js or server.js along side your CRA application. You can use a tool like concurrently to run both your React app and the express app.
The trick is to serve your express app on a different port than the default :8080 that CRA serves on. Usually 8081 is a good choice, as it's a common convention to use port numbers that are close together when developing.
In your React app, you will need to make sure you use the full URL for the express endpoint: http://localhost:8081/query/...
On the server side you are going in the correct direction: you need to setup endpoint which will respond with data based on request. In you example you setup an endpoint for a GET HTTP request. If you will need to pass a complex request (for example add new record to database), consider using POST HTTP requests.
On the client side (in the browser) you will need a library that will assist you in sending requests to your server. I can recommend to try Axios (https://github.com/mzabriskie/axios). Usually if you omit protocol, server name and port, request will be sent to the server from which the page was loaded:
http:127.0.0.1:8001/api/endpoint => /api/endpoint

Is directory traversal via request.url possible?

I'm coming from PHP, where you can inject double dots into a URL to try directory traversal. In NodeJS, it seems that you get the Http webserver automatically removes the double dots from the URL.
For example, if you go to http://example.com/static/../app.js, it seems like Node redirects to http://example.com/app.js, which then throws a 404 in my case, because there is no callback for URLs not starting with /static/.
Is it safe to assume that directory traversal via request.url is not possible in a NodeJS HTTP webserver created using the http package?
I was gonna say that you can be sure that it's not possible, then I tried and I have to say that no, it doesn't seem like the http module removes '/../'. The redirection you saw is done in the browser. So whether it's a security risk or not depends on how your static handler is implemented.
Proof of concept:
// Server
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(req.url);
}).listen(1337);
Curl it:
curl --path-as-is "http://localhost:1337/static/../app.js"
# /static/../app.js
So if you use a homebuilt static handler that just uses path.resolve() you're screwed. Hopefully popular ones like express.static have thought about this, but i haven't tried it.
Update
Express indeed responds with a 404 "Error: Forbidden".

Nodejs to provide 1 api endpoint e one html page

here is my issue.
I never wrote something in node without using express so i find it difficult to create a server with basic APIs.
Basically what I found on the internet is this:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
however I don't see How I can implement /index.html and /getData. This code will run on a Raspberry pie, this is why I shouldnt use libraries. Basically I have no much space.
Many thanks,
h
You'll need to manually inspect the URL in the request and handle each case separate:
var http = require('http');
http.createServer(function (req, res) {
if(req.url == "/index.html") {
fs.readFile("index.html", function(err, text){
res.setHeader("Content-Type", "text/html");
res.end(text);
});
return;
}
if(req.url == "/getData") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('get data\n');
return;
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Just because the code is running on a Pi doesn't mean you can't use modules. Modules don't necessarily take up inordinate space. You'd still have to write the same code many modules have written for you. Modules like Express exist specifically to address the implementation issues you're facing, so you would have to rewrite a router to handle the request for /getData or a file reader for static assets like HTML. Whether you use a module or not, you're going to end up with approximately the same amount of code.
Rather than recreating the wheel, perhaps you just need slimmer modules stripped of the features you don't need. Connect, which Express is based on, is fairly minimal. With either Express or Connect, you can strip out what you don't need. Remember that modules are just a node_modules subdirectory in your project root, so you can remove extraneous things like the tests, examples, and (in several cases) the features you don't need.
Alternatively, there are many slimmer modules like send, which is purely for serving static content like your index page. Journey, which provides JSON-only, is a lean feature set too. The point is there are tons of modules that serve specific needs if Express is too large. The node modules list is a good starting point for finding such modules. Working with node without using modules is kind of like taking a step back to the early days of node when these issues plagued everyone. Of course you can do that, but it has already been done.

nodejs - dependencies (very basic one) - express - > it is a part of nodejs or a plugin

i am very much interested to learn node.js and now.js . While trying to learn node.js , i found this one http://expressjs.com . Is this a part of node.js that i should learn or it is something like a plugin ?
We can create server simply using this :
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Then y some people use that express ? what is the difference ?
Thankyou.
Express is for web development, where Node.js is for anything server-side javascript.
You can look up the Express.js guide which will tell you way more:
http://expressjs.com/guide.html
Express JS is again a sugar layer or utility module for Node JS to routing requests. its not part of node installable as of now.
but apart from that it has few more features like, (as per the website) -
Robust routing Redirection helpers Dynamic view helpers Application
level view options Content negotiation Application mounting Focus on
high performance View rendering and partials support Environment
based configuration Session based flash notifications Built on
Connect Executable for generating applications quickly High test
coverage
http://expressjs.com/

Resources