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

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

Related

NodeJS, Express, and ejs; why does the test fail, but the view works?

I'm working through a PluralSight course/project on NodeJs and Express. They have a project template with tests. The app is working, it is actually finding and rendering the view. But the test for setting the views directory is failing. I have tried many variations of directories for the views, with and without the '/' after the '/views'; I have tried many variations of using the path.join(__dirname, './src/views') as well. Nothing seems to satisfy the test, even when I tried using the same values in the test, as in app.set('views', path.join(__dirname, '../../src/views')) Nothing seems to satisfy the test.
The tests are run with npm run test:module1. When that runs there is a line in the console: mocha --exit './test/module1/*.spec.js' The test is definitely finding the app because it runs 8 tests; 7 pass and only this one fails.
But I'm trying to re-learn modern JS, as well as Express and ejs, so I may be missing something basic.
Here's my app.js code:
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
app.set('views', './src/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, '/public/')))
app.get('/', function(req, res) {
res.render('index', { title: 'Index'});
})
app.listen(3000, function() {
console.log('PS Project Running on port 3000!');
});
and here's their relevant test:
const path = require('path');
describe('View engine and directory', () => {
it('should set view engine and directory #app-set-views-directory-engine', () => {
assert(typeof app === 'function', '`app` const has not been created in `app.js`.');
assert(app.settings['view engine'] === 'ejs', 'The view engine has not been set to `ejs`.');
assert(app.settings.views === path.join(__dirname, '../../src/views'), 'The view directory has not been set to the `views` directory.');
});
});

Deploy App to Heroku - I got Internal Server Error

I worked my first application looking at one tutorial for Mongo / Express / Node. App successfully worked on the localhost port:3000 with nodemon server.js.
I connected GitHub directly with Heroku and get message "Internal Server Error" every time.
I would appreciate if someone knows what the problem is. Although the application functioned on the computer, I wanted to learn how to deploy it on Heroku.
require("./models/db");
const express = require("express");
const path = require("path");
const exphbs = require("express-handlebars");
const bodyparser = require("body-parser");
const employeeController = require("./controllers/employeeController");
var app = express();
app.use(
bodyparser.urlencoded({
extended: true
})
);
app.use(bodyparser.json());
app.set("views", path.join(__dirname, "/views/"));
app.engine(
"hbs",
exphbs({
extname: "hbs",
defaultLayout: "mainlayout",
layoutsDir: __dirname + "/views/layouts/"
})
);
app.set("view engine", "hbs");
app.listen(process.env.PORT || 3000, function () {
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env)
});
app.use("/employee", employeeController);
from your post I can only guess a number of things that could be wrong. Try using heroku logs -t in your terminal (if you have logged in on the heroku cli on your terminal) and comment what you see. It could be that your npm start command is using nodemon (which shouldn't be used for production). It could also be that there is maybe something that isn't in your package.json therefore not being installed on Heroku. If you post what you get on that terminal command I can maybe help you further :)

Something is calling POST /inform in nodejs express project

I have a pretty simple nodejs project that uses express. When I start this project locally I have noticed that something is calling a POST to /inform about every 30 seconds. I'd like to know what's calling inform and what the purpose is.
I'm new to node. Is this normal? I haven't implemented a route for this call so it causes a 404.
Here's my main app:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const fileUpload = require('express-fileupload');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(fileUpload());
// routes
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use((req, res, next) => {
console.log(req)
next(createError(404));
});
// error handler
app.use((err, req, res) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
In my console, I see this about every 30 seconds:
POST /inform 404 14.002 ms - 2158
POST /inform 404 13.910 ms - 2158
POST /inform 404 31.536 ms - 2158
EDIT:
Thank you for the comments. I changed my express port to 8000 and it no longer happens. So something on my local machine is looping and posting to localhost:8080/inform. I'll have to trace this down.
I have a Ubiquity Unify network stack at home. After running (and stopping) the Unifi Controller on my laptop, all my Unify devices continue to send a POST <laptop IP>:8080/inform.
My own application was getting its logged filled up with the same unknown route: "/inform" error.
Solutions:
Choose a different port
Bind your application to 'localhost' instead of '0.0.0.0'
Get a dedicated controller device, like a Raspberry Pi or Unifi Cloud Key
This could be pretty much any application on your PC or even other systems in your local network, if you are listening on public addresses.
You could implement the route to see if the request header/body give any hint as to where this is coming from.
It may also be possible for external software such as Wireshark to monitor network calls to localhost, including their source.
Otherwise use a different port where no one is sending periodic pings to.

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.

Node.js "Uncaught SyntaxError: Unexpected token <" when loading socket.io.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);

Resources