chat app with node.js and socket.io - node.js

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.

Related

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.

Can't load local files when using NodeJS server

I'm very new to NodeJS, and I'm currently playing around with it (and websockets), so this question might be a bit dumb. Anyway, I'm following a tutorial which has given me a simple app.js containing the following:
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
In my index.html I'm trying to load some js and css files, but I can't seem to load them. The files are inside a js folder which is in the same directory as my app.js and index.html, and I'm trying to load them like so:
<script src="/js/script.js"></script>
If I look at the response from the request in my browser, it's returning the content of index.html.
Again, sorry if this question is silly, but I'm stuck and have no clue where to look.
Thanks!
A web server in node.js does not serve ANY files by default (unlike some other web servers). So, if you want js files to be served, you have to define a web server route that will serve them. The code you show returns index.html for all incoming requests coming into that http server so, it should be no surpise that when a request comes in for /js/script.js, your web server sends out index.html.
A typical framework to use with node.js for web serving is Express and it has express.static() that can be used to define a route that will cover all your static files or all files in a particular directory. You could, of course, code your own static file handling or find some other module to do that also. The point is that you have to write or configure some code to serve your static resource files. That is not done for you automatically by the node.js http server.
you can specify to the server in which folder to look for what
for static files such as css, images you can use
public directory, you can provide your custom directory, but it's better to use public ,same goes for views
always require
const PATH = require('path')
app.use(express.static(PATH.join(__dirname, 'public')));
for template files such as .ejs, .html, .jade use
app.set('views', PATH.join(__dirname, 'views'));

Express js routing is downloading file and not rendering it

I am trying to implement a router on the server side with node.js and express.js.
I want to serve a file statically, but I already got this to work for a index.html file I created. No problems there.
My setup has tons of fileName.csp files (i.e. they end in .csp). Anyways, when I try to access a .csp file in the browser (inside it is really just a .html page - but the server side language must have it as a .csp file extension) but when I try to access it, the browser (google chrome) downloads the .csp file instead of rendering it!
I could really use some help since I'm new to all of this.
the line of code that is allowing the download of the .csp file, the code that exposes the directory where the .csp files live, is
app.use('/static', express.static('D:/CACHESYS/CSP/cah/'));
below is pretty much the whole snippet of code
var http = require('http');
var express = require('express');
var app = express();
app.use('/static', express.static('D:/CACHESYS/CSP/cah/'));
app.listen(3000, function() {
console.log('listening on port 3000');
})
app.get('/home', function(request, response) {
response.end('going to /home');
})
app.get('/csp/cah/MARS.csp', function(request, response) {
response.end('Trying to navigate to /csp/cah/MARS.csp');
})
p.s. the actual file path that is being downloaded is
D:/CACHESYS/CSP/cah/fileName.csp
just to give some more context for the question.
any help is appreciated
thanks!
You need to tell express what content type a .csp file is. You can do this with the following line:
express.static.mime.define({
'text/html': ['csp']
});
Although, if the file is an HTML file, it should probably have the .html extension. Also, if you are simply serving static files it is good practice to use an HTTP server like nginx or Apache to do that, rather than Node.js.
The reason this works is express will set the header Content-Type: text/html. This tells the browser it is HTML and it should render it as such. By default if a browser comes across a content type it doesn't recognise, it simply downloads it.

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

Resources