How to use Express in Nodejs - node.js

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});

Related

react and node js serving from single port endpoint not found

Im making a simple app with react and node. On the react side I create a note with a unique-id and then the note can be found at mypage.com/unique-id using react-router-dom and useEffect in the loaded component to get the data from the database. This works perfect as long as my frontend and backend are being served from different ports. When I build the react app and place it in my nodejs app the app will work fine, until I reload mypage.com/unique-id and then im hit with a 404 on my server side. I have a bit of a grasp of what is going on - everything is being served from localhost:3001/ so when i reload localhost:3001/unique-id my server is looking for a route for that, which doesnt exist on my server side. I'm not sure how to connect the dots to serve my front end page at localhost:3001/unique-id with data from the server for that unique id. If i makea route on my server side it would just send back the raw data without serving the page that is suppose ot be at localhost:3001/unique-id
I had faced the same issue and it got resolved by adding * into the route
before route
app.get("/", (req, res) => {
res.header("Cache-Control", "max-age=-1");
res.header("Expires", "-1");
res.header("Pragma", "no-cache");
res.sendFile(path.join(__dirname, "build/index.html"));
});
after
app.get("/*", (req, res) => {
res.header("Cache-Control", "max-age=-1");
res.header("Expires", "-1");
res.header("Pragma", "no-cache");
res.sendFile(path.join(__dirname, "build/index.html"));
});

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

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.

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"));
});

chat app with node.js and socket.io

I'm trying to create a chat app with node.js and socket.io
This is my app.js with addresses scripts
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/game.php');
});
io.sockets.on('connection', function(socket){
socket.on('send message', function(data){
io.sockets.emit('new message', data);
});
});
With .html everything works well
But when i change it to .php instead of loading the page it starts to downloading it
on " localhost:3000"
What should i change to make it work?
If you need the game.php code ask me to post it.
UPDATE:
edited this part
app.get('/', function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.sendfile(__dirname + '/game.php');
});
and now it gives me
ReferenceError: text is not defined
at C:\Users\Mojtaba\Desktop\chat\app.js:9:33
at callbacks (C:\Users\Mojtaba\Desktop\chat\node_modules\express\lib\router\index.js:161:37)
at param (C:\Users\Mojtaba\Desktop\chat\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Users\Mojtaba\Desktop\chat\node_modules\express\lib\router\index.js:142:5)
at Router._dispatch (C:\Users\Mojtaba\Desktop\chat\node_modules\express\lib\router\index.js:170:5)
at Object.router (C:\Users\Mojtaba\Desktop\chat\node_modules\express\lib\router\index.js:33:10)
at next (C:\Users\Mojtaba\Desktop\chat\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.expressInit [as handle] (C:\Users\Mojtaba\Desktop\chat\node_modules\express\lib\middleware.js:31:5)
at next (C:\Users\Mojtaba\Desktop\chat\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.query [as handle] (C:\Users\Mojtaba\Desktop\chat\node_modules\express\node_modules\connect\lib\middleware\query.js:44:5
What determines if a browser shows a file as a downloaded attachement or if it should open it directly is the Content-Disposition HTTP header.
Try to add this before sending the file:
res.setHeader('Content-Disposition', 'inline');
and now the browser should no longer treat the file as an attachment. What is probably happening is that express is looking at the extension of the file and as it does not recognize the PHP extension it sends the file back as an attachment.
But the opened file should not display as you want in the browser, as the browser cannot interpret PHP. PHP files are meant to be interpreted in the backend and not sent to the browser.
You can use PHP as a view engine in express using for example php-node, buy i don't think it's a very frequent combination.
The default view engine for express is jade, mustache is also frequently mentioned as well as handlebars.
If you prefer your templating engine on the client side instead of the server side, check angular.js.
Before going on it's important to understand that sending PHP files to the browser is not the solution for the problem being solved, read some an article or two first on the differences between server side and client side templating.

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.

Resources