Deploying Vue file in Express is not working as expected - node.js

I am having one simple vue file (index.html)
<html>
<body>
<div id="example">
<p>{{ hello }}</p>
</div>
</body>
</html>
<script src="js/app.js"></script>
<script>
new Vue({
el: '#example',
data: { hello: 'Hello world!' }
})
</script>
When opening the index.html file in browser, it is printing Hello world. I need to deploy this in express server. Added server.js file as below,
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 1234;
// sendFile will go here
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/public/index.html'));
});
app.listen(port);
console.log('Server started at http://localhost:' + port);
When running node server, browser is just rendering like below,
If I replace the <script src="js/app.js"></script> with <script src="https://cdn.jsdelivr.net/npm/vue#2.6.14/dist/vue.js"></script>, it is working fine. Dont know why it is not working when using Vue library as external file. Is there any way to achieve this? Thanks in advance.

Just add this line of code
app.use(express.static(path.join(__dirname, 'public')));
So you code would look like this
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 1234;
app.use(express.static(path.join(__dirname, 'public')));
// sendFile will go here
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/public/index.html'));
});
app.listen(port);
console.log('Server started at http://localhost:' + port);

Related

Node use socket.io with ejs and router

I tried to get socket.io to run, but I always get a client error, so I think there is a logic bomb inside the code.
app.js
const express = require('express');
const app = express();
const router = express.Router();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.set('socketio', io);
const expressLayouts = require('express-ejs-layouts');
module.exports = router;
app.use(express.static(__dirname));
app.use(express.urlencoded({ extended: true }));
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.use(function(req, res, next) {
next();
});
io.on('connection', function(socket){
console.log('a user connected');
});
app.use('/', require('./routes/test.js'));
const PORT = process.env.PORT || 8081;
app.listen(PORT, console.log(`Server started on port ${PORT}`));
Inside the route file I open the page
test.js
const express = require('express');
const router = express.Router();
// Dashboard
router.get('/start', (req, res, next) => {
res.render('index2', {
caseArray: 'eins'
});
});
module.exports = router;
And finally inside the template I added:
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"
></script>
<script src="/socket.io/socket.io.js"></script>
<script>var socket = io();</script>
But I always get an error message inside the browser console:
GET http://localhost:8081/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)
(index):24 Uncaught ReferenceError: io is not defined
at (index):24
As I understand from all the tutorial is, that node will send the socket.io within the request to the html page and that with the html page the server get connected. But there is no connection message because the files do not exists. Where is my problem? In client or server?
It seems node is trying to locate socket.io's js files on your server on the route /socket/socket.io.js which I assume you haven't defined
I would suggest you use Socket io's cdn link and place it between your html header tags
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js'></script>
For all with a similar problem. I solved it by using
server.listen(PORT, console.log(`Server started on port ${PORT}`));
instead of using
app.listen(PORT, console.log(`Server started on port ${PORT}`));

Node express server isn't working - how to create and start a server?

I am trying to create and start a server and I've been looking at other code and can't see why mine isn't working (just getting this: localhost just keeps loading and loading and nothing happens).
Any ideas? Thanks!!!
app/server/app.js :
'use strict'
var express= require ('express');
var path=require('path');
var bodyParser = require('body-parser');
var http = require('http');
var app= express();
module.exports = app;
app.use(express.static(path.join(__dirname, '../browser')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = http.createServer();
server.listen(1337, function () {
console.log('Server is listening on port 1337!');
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(err.message);
});
app/browser/index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<title>node</title>
</head>
<body>
<div>
<p>Hey whats up</p>
</div>
</body>
</html>
Your code works for me.
The only thing wrong in your code is you have to change server.listen(1337, function ()..., to app.listen(1337, function () {...
Also, I added a file path...
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '/index.html'));})
...to link your localhost:1337 to your index.html file. Now your index.html file will display when you go to localhost:1337.
Lastly, I'm not sure if you need this line... var server = http.createServer();. I deleted it and everything worked fine.
Here's the code below.
'use strict'
var express= require ('express');
var path=require('path');
var bodyParser = require('body-parser');
var http = require('http');
var app= express();
module.exports = app;
app.use(express.static(path.join(__dirname, '../browser')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '/index.html'));
})
app.listen(1337, function () {
console.log('Server is listening on port 1337!');
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(err.message);
});
Maybe the port You wrote - 1337 is busy, check by choosing other port, for example 4200, or 3000 - server.listen(4200,function () {

ExpressJs View helpers do not work

It's probably a newbie question. I'm trying to setup my very first expressjs application and I need to use a view helpers that doesn't work for some reason.
Here is my server.js
var express = require('express');
var app = express();
var test = function(req, res, next) {
res.myLog = function(){
console.log("res");
return "Hello";
}
next();
}
app.use(test);
app.get("*", function(req, res) {
res.sendfile('./dist/index.html');
})
app.listen(5000);
And index.html
<html>
<head>
<title>Test application</title>
<link rel="stylesheet" href="main.css" />
<script src='<%=myLog()%>'></script>
</head>
<body>
<h1>Yo World!</h1>
</body>
</html>
myLog function is not call during rendering. Originally I was trying to use some third part helpers and they didn't work as well.
I haven't found any documentation of how to use the helpers on expressjs site. I'm clearly doing something wrong here.
Express version 4.3.14
To send file using express, correct ways is:
//sending html files
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:5000
app.get('/', showClientRequest, function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
function showClientRequest(req, res, next) {
var request = {
REQUEST : {
HEADERS: req.headers,
BODY : req.body
}
}
console.log(request)
return next();
}
app.listen(5000);
Use ejs template engine:
var express = require('express');
var ejs = require('ejs');
var app = express();
app.set('view engine', 'ejs');
var path = require('path');
// viewed at http://localhost:5000
app.get('/', showClientRequest, function(req, res) {
res.render('index',{message:"Hello World!"});
});
function showClientRequest(req, res, next) {
console.log('Something Here...');
return next();
}
app.listen(5000);
Node-Cheat Available:
For complete code, get working node-cheat at express_server run node app followed by npm install express ejs.
Use res.locals.myLog instead of res.myLog to set locals. If you don't need req within your helper function you can also use app.locals.myLog.
res.sendfile will not render your view but just send a file as it is. You will have to use res.render and move your dist/index.html to views/index.ejs.

Socket.io automatically serves its client-side javascript, when you wire it to the server

Here's a minimal example of node.js/express.js/socket.io server. It shouldn't be serving anything but index.html from / path.
server.js:
var path = require('path');
var express = require('express');
var http = require('http');
var socketio = require('socket.io');
// create server
var app = express();
var server = http.createServer(app);
var io = socketio(server);
// set routes for express
app.get('/', function(req, res){
console.log('index.html is NOT served by static middleware');
res.sendFile(path.resolve(__dirname + '/../client/index.html'));
});
// start listening
server.listen(9000, function(){
console.log('listening on 9000');
});
I run it with node server.js command. It serves index.html as localhost:9000/ successfully.
But for some strange reason it also serves /socket.io/socket.io.js from node_modules directory, which it shouldn't. Why? Here's my index.html file:
index.html
<!doctype html>
<html>
<head>
<title>Websocket + RabbitMQ + Express</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
<div id="messages"></div>
</body>
</html>
If it's about simplicity, there's no need for socket.io and http if you're using express. Try this code below for your server.js:
var path = require('path');
var express = require('express');
var app = express();
app.get('/', function (req, res) {
console.log('index.html is NOT served by static middleware');
res.sendFile(path.resolve(__dirname + '/../client/index.html'));
});
app.listen(9000, function () {
console.log('Example app listening on port 9000!');
})
This way, only client will resolve socket.io and server will only be responsible for serving a static page

Socket.io and Express 3

I created a express 3 app with the express generator and installed socket.io.
On app.js im emiting a message:
io.sockets.on('connection', function(socket) {
socket.emit('init', { msg: 'Welcome'});
});
At server side I wrote:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src='/socket.io/socket.io.js' />
<script>
var socket = io.connect('http://127.0.0.1:3000');
socket.on('init', function (data) {
console.log(data.msg);
});
</script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
If I run app.js It should print "Welcome" on the console, but its not priting anything. I checked if /socket.io/socket.io.js is accesed and it does.
When running the app I get:
info - socket.io started
Express server listening on port 3000
GET / 200 28ms - 472
GET /stylesheets/style.css 200 163ms - 110
debug - served static content /socket.io.js
Am I missing something? I followed the socket.io webpage examples, but it seems that server is running fine... maybe something at the client-side?
EDIT: I also tried var socket = io.connect('http://127.0.0.1', { port: 3000 } ); on the client side, and also running all socket client side from the body.
Doing a console.log on the io.sockets.on event gave nothing... so "connection" is never reached.
app.js:
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
var server = http.createServer(app)
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', routes.index);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = require("socket.io").listen(server)
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
});
index.html:
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
});
</script>
In your browser's console you should see an object containing "hello": "world".
adding a index.jade file to the example I posted before
server.js
var app = require('express')()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server)
server.listen(3000)
io.set('loglevel',10) // set log level to get all debug messages
io.on('connection',function(socket){
socket.emit('init',{msg:"test"})
})
app.get('/',function(req,res){
res.render('index.jade')
})
/views/index.jade
doctype html
html
head
script(src="/socket.io/socket.io.js")
script.
var sockets = io.connect()
sockets.on('init',function(msg){
alert(msg.msg)
})

Resources