App.js functionality loss over public internet using NODE JS AND EXPRESS - node.js

Node js + express is displaying great on localhost. My issue is, is that after I display static page which is doing it's job, my app.js script is not firing from the outside world. But when running locally it works like it is suppose to.
//send html page to user
app.use(express.static(__dirname + '/node_modules'));
app.use(express.static('public'));
app.get('/', function(req, res, next) {
res.sendFile(__dirname + '/index.html'); //send the file
});
//My app
// everything below this line does not work
I followed the direction from express but still app.js is not firing from the outside world. Again it hits great on local. Any help that would be greatly appreciated!
https://expressjs.com/en/starter/static-files.html

Based on your code, I was able to deduce that you are behind a sockets enabled CDN and it has not cashed your server-side sockets. Turn off cashing if you are actively developing your site.

Related

How to create a node based server to serve REST API and also deploy the application.

I am new to nodeJS server area, need help in understanding how to work with REST API (using express) and deploy the angular application over a singe node server and same ports.
By deploying i want to understand if user hit below url http://localhost:8000/<page_name> then the specified page should open.
And is user hit below url using get or post request
http://localhost:8000/api/<api_name> then a json or a text will be returned.
How to run both the thing over a single node server.
Lets assume, you have all your static files in the /public folder of you app. Generally spoken, if you are using express.static, you should also get your index.html because this is handled by default for each directory.
In your case, as you are using Angular, the routing is handled from the client side (SPA). You should only have one single index.html after building your Angular app. All files from your dist folder should then be placed into your /public folder. Then you need to make sure, that initial file serving provides your index.html like so:
In this example static files are served first, then your API and if nothing is found, you are getting back you index file.
const express = require('express');
const app = express();
// serve static files
app.static(__dirname + '/public'));
// serve your API
app.get('/api/welcome', function (req, res) {
res.send('Welcome');
});
// fallback routing (server side handling)
app.get(/.*/, function (req, res) {
res.sendFile(__dirname + ‘/public/index.html‘
});
app.listen(3000);
Next time please make sure, to give all necessary information in your question ;-)
With the help from Sebastian, so far I can find a solution but its not working when i am hitting URL for different pages.
const express = require('express');
const app = express();
app.use(express.static('public'))
Please provide your suggestions.

Node React structure without view engine

I'm new to node. I was using express-handlebars as my view-engine, but now I've added React and I understood that I no longer require handlebars. The problem that I'm having is that in order to get to the index.html page, without handlebars, I had to use
app.use(express.static('./public'));
Everything gets rendered from react, but what if I want to do some other things when the user goes to the index page like
app.get("/",function(req,res){
console.log("connected");
});
If I add the get request after exporting the static files, the console.log never gets called. If I use it before, it does get called, but I can see the page loading forever. How should I structure the application now that I'm using react and I don t have a view engine anymore?
In your specific case, if you don't want to render anything to the user, you should turn your function into a middleware :
app.get("/",function(req,res, next){
console.log("connected");
next();
});
and put it before the app.use(express.static('./public'));
However, if you want to do actual logic with return values and such, I would suggest that you setup some kind of API that you request using Ajax from the client.
You can check my repository
https://github.com/kennethmervin01/react-node-production
it's a boilerplate to serve react app in node.js/express
then check my code inside app.js
You just need to copy the production build of your react app inside the react folder
app.use(express.static(path.join(__dirname, "../react")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "../react", "index.html"));
});

How to use AngularJS routes with Express (Node.js) when a new page is requested?

I'm using Express, which loads AngularJS from a static directory. Normally, I will request http://localhost/, in which Express serves me my index.html and all of the correct Angular files, etc. In my Angular app, I have these routes setup, which replace the content in an ng-view:
$routeProvider.when('/', {
templateUrl: '/partials/main.html',
controller: MainCtrl,
});
$routeProvider.when('/project/:projectId', {
templateUrl: '/partials/project.html',
controller: ProjectCtrl,
});
$locationProvider.html5Mode(true);
On my main page, I have a link to <a href="/project/{{project.id}}">, which will successfully load the template and direct me to http://localhost/project/3 or whatever ID I have specified. The problem is when I try to direct my browser to http://localhost/project/3 or refresh the page, the request is going to the Express/Node server, which returns Cannot GET /project/3.
How do I setup my Express routes to accommodate for this? I'm guessing it will require the use of $location in Angular (although I'd prefer to avoid the ugly ?searches and #hashes they use), but I'm clueless about how to go about setting up the Express routes to handle this.
Thanks.
with express 4, you probably want to catch all requests and redirect to angularjs index.html page.
app.use(app.router); doesn't exist anymore and res.sendfile is deprecated, use res.sendFilewith an uppercase F.
app.post('/projects/', projectController.createProject);
app.get('/projects/:id', projectController.getProject);
app.get('*', function (req, res) {
res.sendFile('/public/index.html');
});
put all your API routes before the route for every path app.get('*', function (req, res){...})
I would create a catch-all handler that runs after your regular routes that sends the necessary data.
app = express();
// your normal configuration like `app.use(express.bodyParser());` here
// ...
app.use(app.router);
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/public/index.html');
});
app.router is the middleware that runs all of your Express routes (like app.get and app.post); normally, Express puts this at the very end of the middleware chain automatically, but you can also add it to the chain explicitly, like we did here.
Then, if the URL isn't handled by app.router, the last middleware will send the Angular HTML view down to the client. This will happen for any URL that isn't handled by the other middleware, so your Angular app will have to handle invalid routes correctly.
I guess I should have clarified that I wasn't interested in using a template engine, but having Angular pull all of the HTML partials on it's own, Node is functioning completely as a static server here (but it won't be for the JSON API. Brian Ford shows how to do it using Jade here: http://briantford.com/blog/angular-express.html
My app is a single-page app, so I created an Express route for each possible URL pattern, and each of them does the same thing.
fs.readFile(__dirname + '/public/index.html', 'utf8', function(err, content) {
res.send(content);
});
I was assuming I would have to pass some request variables to Angular, but it looks like Angular takes care of it automatically.

How to use Express in Nodejs

While using express in Node.js how to connect it with the client?
Do we need a .js file to be included in on the client side?
The goal is to make a client side with a "connec"t button and when I click that button the client is connected to the server and the server return is alerted on the page.
var app = require('express').createServer();
app.get('/', function(req, res){
res.send('hello world');
});
app.get('message', function(req, res){
console.log(req);
});
app.listen(3000);
Express is a web development framework (the intended client is a web browser).
In the application's root directory type node app.js and then open http://localhost:3000 in your browser
you can add jade file in the view folder and add the button to it and on click event , give the url to be called if that url matched with the app.get of the server code, do the work and after finishing render it back to the page u want with changes.
for rendering use res.render('index');
u can also pass results with it,
res.render('index',{result:result});

Node.js + Express without using Jade

Is it possible to use express without any template engine?
Yes,
app.get('/', function(req, res){
res.render('index.html');
});
should just work
UPDATED
Some might have concerns that sendFile only provides client side caching. There are various ways to have server side caching and keeping inline with the OP's question one can send back just text too with send:
res.send(cache.get(key));
Below was the original answer from 3+ years ago:
For anyone looking for an alternative answer to PavingWays, one can also do:
app.get('/', function(req, res) {
res.sendFile('path/to/index.html');
});
With no need to write:
app.use(express['static'](__dirname + '/public'));
For anyone having the need to immediately use regular HTML without jade in a new express project, you can do this.
Add a index.html to the views folder.
In app.js change
app.get('/', routes.index);
to
app.get('/', function(req, res) {
res.sendfile("views/index.html");
});
UPDATE
Use this instead. See comment section below for explanation.
app.get('/', function(req, res) {
res.sendFile(__dirname + "/views/index.html");
});
You can serve static files automatically with Express like this:
// define static files somewhere on top
app.use(express['static'](__dirname + '/your_subdir_with_html_files'));
Actually this should be express.static(...) but to pass JSLint above version works too ;)
Then you start the server and listen e.g. on port 1337:
// app listens on this port
app.listen(1337);
Express now serves static files in /your_subdir_with_html_files automatically like this:
http://localhost:1337/index.html
http://localhost:1337/otherpage.html
This is all out of date - correct answer for 3x, 4x is
The second answer here:
Render basic HTML view?
In your main file:
app.get('/', function(req, res){
res.render('index');
});
Your index.jade file should only contain:
include index.html
where index.html is the raw HTML you made.

Resources