Node.js "Uncaught SyntaxError: Unexpected token <" when loading socket.io.js - node.js

I have simple application to test socket.io using node.js and express framework
There are some files relating to my app
File server.js
var express = require('express');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
var http = require('http');
var server = http.createServer(app);
var config = require('./server/config/config')[env];
require('./server/config/express')(app, config);
/////////////////////////// Database ////////////////////////////////
require('./server/config/mongoose')(config);
/////////////////////////// Passport ////////////////////////////////
require('./server/config/passport')();
/////////////////////////// Routes ////////////////////////////////
require('./server/config/routes')(app);
/////////////////////////// Socket ////////////////////////////////
require('./server/config/socket')(server);
/////////////////////////// Port ////////////////////////////////
app.listen(config.port);
console.log("Listening on port " + config.port + '...');
File express.js
var express = require('express'),
stylus = require('stylus'),
passport = require('passport');
module.exports = function(app, config){
function compile(str, path){
return stylus(str).set('filename', path);
};
app.configure(function(){
app.set('views', config.rootPath + '/server/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({secret: 'test whiteboard unicorns'}));
app.use(passport.initialize());
// using session
app.use(passport.session());
// config Stylus middleware
app.use(stylus.middleware({
src: config.rootPath + '/public',
compile: compile
}));
app.use(express.static(config.rootPath + '/public', { redirect : false }));
});
}
script.jade
script(type="text/javascript", src="/vendor/jquery/dist/jquery.min.js")
script(type="text/javascript", src="/vendor/angular/angular.js")
script(type="text/javascript", src="/vendor/bootstrap/dist/js/bootstrap.min.js")
script(type="text/javascript", src="/vendor/toastr/toastr.min.js")
script(type="text/javascript", src="/vendor/restangular/dist/restangular.min.js")
script(type="text/javascript", src="/vendor/lodash/dist/lodash.min.js")
script(type="text/javascript", src="/vendor/jquery-minicolors.min.js")
script(type="text/javascript", src="/socket.io/socket.io.js")
When I start with nodemon server.js, node.js console runs quite OK
[nodemon] starting `node server.js`
connect.multipart() will be removed in connect 3.0
info - socket.io started
Listening on port 3030...
However, when I open browser and test app, I see errors in console
Uncaught SyntaxError: Unexpected token < jquery-minicolors.min.js:1
Uncaught SyntaxError: Unexpected token < socket.io.js:1
I just don't know why these errors happens and how to fix them
Thanks

This means that jquery-minicolors.min.js is actually an html document. make sure that the route is correct.
You're getting the same error on socket.io.js, make sure that when you hit "localhost:3030/socket.io/socket.io.js" that you are actually getting something.
Either way, the "unexpected <" comes from a 404 error html page.

I am running an app built using JQuery Html and Css on browser using VS 2017 IDE. The app wouldn't run with a Chrome spinning wheel.
I unchecked the below checkbox and the app started running.
It might help someone some day.

I had this error too when setting up the server using node.js. The problem was that in server.js file I initialized the socket.io library with http argument before I created the server.
So I had
var http = require('http');
const io = require('socket.io', 'net')(http);
http.createServer(function(res,req) {
...
});
Corrected it to:
var http = require('http').createServer(handler);
const io = require('socket.io', 'net')(http);

Related

How to fix recent node.js errors from my apps?

const express = require("express");
const path = require("path");
var hbs = require("express-handlebars");
const morgan = require("morgan");
const middlewares = require("./middlewares/middlewares");
const PORT = process.env.PORT || 3002;
var app = express();
// setup static file service
app.use(express.static(path.join(__dirname, "static")));
//Setup app port
app.set("port", process.env.PORT || PORT);
// setup handlebars and the view engine for res.render calls
app.set("view engine", "html");
app.engine(
"html",
hbs({
extname: "html",
defaultView: "default",
layoutsDir: __dirname + "/views/layouts/",
partialsDir: __dirname + "/views/partials/"
})
);
app.get("/", (req, res) => {
res.send("Hello world");
});
app.use(morgan("common"));
app.use(middlewares.errorHandler);
app.use(middlewares.ignoreFavicon);
app.use(middlewares.notFound);
var server = app.listen(app.get("port"), () =>
console.log(`Server started...Listening on port: ${PORT}`)
);
This is my basic server setup. Whenever I request a route I get the following errors in my console. I had to add middleware ignoring this route as well. "GET /favicon.ico HTTP/1.1"
Uncaught TypeError: Cannot convert undefined or null to object
at Function.keys ()
at contentscript.bundle.js:72
at S.Object.isExtensible.Object.isExtensible.e.___hb.e.___hb (contentscript.bundle.js:29)
[Honeybadger] Unable to send error report: no API key has been configured.
is there more of a stack trace? Also, when you say "console", do you mean in the Node console, or in the browser console? It looks like the log message is from our client-side JavaScript package, which I would expect in the browser. If you're catching errors in your Node application, you should use our Node.js package.
In honeybadger.js, ___hb can sometimes appear in stack traces because the function was wrapped by our library, but the error is often still in your project code. I would suggest configuring Honeybadger with an API key if you're trying to diagnose errors in production.
Related docs:
https://docs.honeybadger.io/lib/javascript/index.html
https://docs.honeybadger.io/lib/node.html

Angular2 application with NodeJS not loading everything

I'm experimenting with Angular2 and, with the quick start guide on their official documentation, I'm definitely up and running. However, if I want to do any APIs on the server or host it on the cloud it seems I'll need to use Node. I think I have everything set correctly in the server.js file, yet when I run it it seems like it's not loading everything from SystemJS and I get the following errors:
Here is the Node code:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var System = require('systemjs');
// loads './app.js' from the current directory
System.import('app').then(function(m) {
console.log(m);
});
// Config
app.set('port', (process.env.PORT || 3000));
app.use('/app', express.static(__dirname + '/app'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(app.get('port'), function() {
console.log('MEAN app listening on port ' + app.get('port'));
});
app.get('*', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
I'm not sure what I'm missing to include in the Node side that gets included when running lite-server from npm start that is included from the Angular2 quick start guide.
When you are telling express where to look for the static files, you have to include where your js files will be as well.
For example, in one of my projects I have it like so
app.use('/css', express.static(path.resolve(appPath, 'css')));
app.use('/lib/css', express.static(path.resolve(appPath + '/lib', 'css')));
app.use('/lib/js', express.static(path.resolve(appPath + '/lib', 'js')));
app.use('/assets', express.static(path.resolve(appPath, 'assets')));
app.use('/node_modules', express.static(path.resolve(appPath, 'node_modules')));
app.use('/app', express.static(path.resolve(appPath, 'app')));
I believe that might be your issue or hopefully set you in the right path.

Scripts and css files not loading with jade + node js

I am learning mean stack development. I am using working out with some examples. I am trying to load my css files and javascript files in the jade file. files are appearing in the console --> Sources. But all the css files are loading with empty data and all the js files are loading with html data.
I am having my server.js like this
var express = require("express");
var stylus = require("stylus");
var logger = require("morgan");
var bodyParser = require("body-parser");
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
function compile(str,path) {
return stylus(str).set('filename', path);
}
app.set('views', __dirname + '/server/views');
app.set('view_engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(stylus.middleware({
src: __dirname + '/public',
compile:compile
}));
//defining routes
app.get('*', function (req,res) {
res.render('index.jade');
});
var port = 3030;
app.listen(port);
console.log('starting listening....');
How to load the files properly in this scenario?
The requests for client side resources are not being handled by anything in your app, which means they get handled by your "catch-all" handler (app.get('*', ...)), which returns HTML (which explains why you are seeing HTML being returned for jQuery, for instance).
You want to use a static file handler in your app to handle those requests:
app.use(express.static(__dirname));
The __dirname argument points to the directory that holds your client side resources files, so you may need to change this.
Also, make sure that you add this line above your catch-all handler, otherwise the requests will still be handled by that instead of the static file handler.

Using connect-livereload in an Express node app

Following this great article on how to use npm as a build tool, I would like to implement it when building a nodejs express web app.
My node app is created on port 8080, this is a simplified version of my server.js file:
var env = process.env.NODE_ENV
var path = require('path');
var express = require('express');
var logger = require('morgan');
var routes = require('./routes');
var app = express();
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express)
var Oneday = 86400000;
app.use(express.static(__dirname + '/www', {
maxAge: env == 'development' ? 0 : Oneday
}));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, '/public'), {
maxAge: env == 'development' ? 0 : Oneday
}))
if (env == 'development') {
// var liveReloadPort = 9091;
app.use(require('connect-livereload')({
port: 8080
// src: "js/"
// port: liveReloadPort
}));
}
routes.blog(app);
routes.frontend(app, passport);
app.use(function(err, req, res, next) {
console.log(err.stack);
res.status(500).send({
message: err.message
})
});
app.listen(app.get('port'));
console.log('Server starting on port: ' + app.get('port'));
The file that I'm watching before needing to reload is in www/js.
I am using npm as a build tool and before launching server.js with npm I launch a separate process that does watchify source/js/app.js -v -o wwww/js/bundle.js
I did checked that watchify works correctly, updating as I save my files. But there is no livereload once a file is changed.
The error I get in the console is:
Uncaught SyntaxError: Unexpected token <
and I can see that connect-livereload inserted this script in the html:
<script>
//<![CDATA[
document.write('<script src="//' + (location.hostname || 'localhost') + ':8080/livereload.js?snipver=1"><\/script>')
//]]>
</script>
<script src="//localhost:8080/livereload.js?snipver=1"> </script>
I tried also to use live-reload as mentionned in the original article but without success and I am not sure it's the right plugin to use as live-reload launches a server, when I already start one with express.
Any ideas?
connect-livereload only inserts the script into the html (so that you don't need a browser plugin).
you still need a separate livereload server, try node-livereload, grunt-contrib-connect or grunt-contrib-watch ... since you want to use npm as build tool, the first one should be recommendable.
then you would have to change the livereload port to the running live-reload server port (default port is 35729):
app.use(require('connect-livereload')({
port: 35729
}));
The server you tried: live-reload should work as well.
Can you try and start it with:
live-reload [<path>...] --port=35729 --delay=someDelay
and change the connect-livereload option to:
app.use(require('connect-livereload')({
src: "localhost:35729"
}));
This answer shows how to set up livereload to refresh changes to both front and backend files to browser. It might be of help to you. https://stackoverflow.com/a/60542132/5032692

After restructuring my node/express app, my static route to index.html will not work

I'm wanting to server index.html as a default, as I'm using angular to handle client side routes.
Here's the structure of my app.
Here is app/app.js
var express = require('express'),
config = require('./config/config'),
bodyParser = require('body-parser'),
app = express(),
router = express.Router();
require('./config/db')(function(db) {
require('./routes/routes')(app, router, null, db);
app.use(express.static(__dirname, '/'));
app.use(bodyParser.json());
app.use('/', router);
app.listen(config.port);
console.log('Listening on port ' + config.port);
});
The only thing in ./routes/routes.js are server side routes. I'm really not sure what I did, but index.html used to load by default and then angular took care of the rest.
I'm new to node/express.
Error I keep getting is "Cannot get/"
Any help is appreciated!
you should use
app.use(express.static(path.resolve('./public')));
on the express configuration
in your route you need to have one to serve your root path
module.exports = function(app) {
// Root routing
var core = require('/controllers/core');
app.route('/').get(core.index);
};
your server controller
exports.index = function(req, res) {
res.render('index'); //assuming that you are using some view engine.
};

Resources