I have a little problem with this simple code to start a server with nodejs and Hapi.
This is the code:
var Hapi = require('hapi');
var http = new Hapi.Server('0.0.0.0', 8080);
http.route({
method: 'GET',
path: '/api',
handler: function(request, reply) {
reply({ 'api' : 'hello!' });
}
}
);
http.start();
and this is the error :
http.route({
^
TypeError: undefined is not a function
at Object.<anonymous> (C:\Users\Prova.js:8:6)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
It' a very basilar code but i can't understand why it has a problem with http.route.
In hapi 0.8.4 you can add routes with addRoute():
var Hapi = require('hapi');
// Create a server with a host and port
var server = new Hapi.Server('localhost', 8000);
// Define the route
var hello = {
handler: function (request) {
request.reply({ greeting: 'hello world' });
}
};
// Add the route
server.addRoute({
method: 'GET',
path: '/hello',
config: hello
});
// Start the server
server.start();
But that version of hapi is very old, you should upgrade it to the latest. The current stable version of hapi is 8.8.0.
Related
The project runs without any errors when run from Visual Studio Code by runung the cmd : npm start.
But when runing the project as a windows service I´m getting an error about the PORT.
The PORT=8080 is initialized in the (Environment file) env. file.
Bellow is the env. file:
NODE_ENV=production
# hapi server config
PORT=8080
HOST=localhost
HOST_URL=http://localhost:8080
COOKIE_ENCRYPT_PWD=xxxxxxxxxx...
#sql server config
SQL_USER=xxxxx
SQL_PASSWORD=xxxxxxxx
SQL_DATABASE=xxxxxxxx
SQL_SERVER=computer\SQLEXPRESS
SQL_ENCRYPT=false
#okta config
OKTA_ORG_URL=https://dev-000000.okta.com
OKTA_CLIENT_ID=xxxxxxxx
OKTA_CLIENT_SECRET=xxxxxxxxxxx
Bellow is the config file:
"use strict";
const dotenv = require( "dotenv" );
const assert = require( "assert" );
dotenv.config();
const {
PORT,
HOST,
HOST_URL,
COOKIE_ENCRYPT_PWD,
SQL_SERVER,
SQL_PORT,
SQL_DATABASE,
SQL_USER,
SQL_PASSWORD,
OKTA_ORG_URL,
OKTA_CLIENT_ID,
OKTA_CLIENT_SECRET
} = process.env;
const sqlEncrypt = process.env.SQL_ENCRYPT === "false";
assert( PORT, "PORT is required" );
assert( HOST, "HOST is required" );
module.exports = {
port: PORT,
host: HOST,
url: HOST_URL,
cookiePwd: COOKIE_ENCRYPT_PWD,
sql: {
server: SQL_SERVER,
port: SQL_PORT,
database: SQL_DATABASE,
user: SQL_USER,
password: SQL_PASSWORD,
options: {
encrypt: sqlEncrypt,
enableArithAbort: true
}
},
okta: {
url: OKTA_ORG_URL,
clientId: OKTA_CLIENT_ID,
clientSecret: OKTA_CLIENT_SECRET
}
};
the error is as follows:
assert.js:386
throw err;
^
AssertionError [ERR_ASSERTION]: PORT is required
at Object.<anonymous> (C:\inetpub\apis\routis\src\config.js:25:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:903:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (C:\inetpub\apis\routis\src\index.js:3:16)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: true,
operator: '=='
}
extension of dotenv file is .env, Check once for that.
I am creating an API, so I want to add a user system and validate access to the API.
This would be the middleware for validation:
'use strict'
const jwt = require('jwt-simple');
const moment = require('moment');
const config = require('../settings/config');
function isAuth(req, res, next) {
if (!req.headers.authotization) {
return res.status(403).send({
message: `No tiene autorizacion`
})
}
const token = req.headers.authotization.split(" ")[1];
const payload = jwt.decode(token, user, config.token.secret_token);
if (payload.exp <= moment().unix()) {
return res.status(401).send({
message: 'El token ha expirado'
})
req.user = payload.sub;
next();
}
}
module.exports = isAuth;
while this would be the route:
'use strict'
const express = require('express');
const router = express.Router();
const auth = require('../middlewares/auth');
router.get('/', auth.isAuth, (req, res) => {
res.status(200).send({
message: `Tienes acceso`
})
})
on the other hand, this is my main application settings (app.js):
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const config = require('./config')
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
// Routes variables
const productRouter = require('../routes/product');
const privateRouter = require('../routes/private');
// Routes uses
app.use('/api/product', productRouter);
app.use('/private', privateRouter);
app.listen(config.app.port, err => {
if (err) throw err;
console.log(`Server listening on port ${config.app.port}`)
})
module.exports = app;
I am getting this error:
D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object
Undefined]
at Route. [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202:15)
at Function.proto. [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:510:19)
at Object. (D:\api-rest-carlos-azaustre\routes\private.js:6:8)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (D:\api-rest-carlos-azaustre\settings\app.js:15:23)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18) [nodemon] app crashed - waiting for file changes before starting...
And sometimes this line is added at the top of error:
(node:3092) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners > added to [Bus]. Use emitter.setMaxListeners() to increase limit
After reading the answers, I edit my question. I have placed only auth and not auth.isAuth and I am getting the following error:
D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a
Object
at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:458:13)
at Function. (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:220:21)
at Array.forEach ()
at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:217:7)
at Object. (D:\api-rest-carlos-azaustre\settings\app.js:20:5)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (D:\api-rest-carlos-azaustre\index.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14) [nodemon] app crashed - waiting for file changes before starting...
Does anybody know what is it due to?
module.exports = isAuth; means you're only exporting the function and nothing else. That means when you do const auth = require('../middlewares/auth');, auth is the actual function, not an object containing isAuth as a property.
So, doing router.get('/', auth, (req, res) => { should work, instead of auth.isAuth which is invalid.
Learn more about modules here: https://js.evie.dev/modules
Yes, you export the function with this code: module.exports = isAuth;
But then you call use it like this: auth.isAuth
Assuming you're doing something like const auth = require('./bin/auth.js'); or whatever
auth would be the function itself -- there will be no isAuth property.
So you should try this:
router.get('/', auth, (req, res) => {
You haven't posted your entire code, so this is just a best guess.
I don't know why can't I let my API listen on 4000,and my server also doesn't work , and it always says can't not find this "/etc/letsencrypt/live/awiclass.monoame.com/privkey.pem " file !!!!!! and the result should be server socket 4040 , api 4000. API listen on 4000
write on the command line:
npm i socket.io express -s
var fs = require('fs')
//https的一些設定
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/awiclass.monoame.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/awiclass.monoame.com/fullchain.pem')
}
//https & socket port
var https = require('https').createServer(options);
https.listen(4040)
var io = require('socket.io')(https);
console.log("Server socket 4040 , api 4000")
//api port
var app = require('express')();
var port = 4000;
app.listen(port, function(){
console.log('API listening on *:' + port);
});
var messages = [];
//用api方式取得
app.get('/api/messages',function(req,res){
res.send(messages);
})
io.on('connection', function(socket){
//初始化...
console.log("A user connected.");
io.emit("allMessage",messages);
socket.on('sendMessage',function(obj){
//get all message!
messages.push(obj);
console.log( obj.message + " - " + obj.name )
io.emit('newMessage', obj);
})
})
Error: ENOENT: no such file or directory, open
'/etc/letsencrypt/live/awiclass.monoame.com/privkey.pem'
at Object.fs.openSync (fs.js:646:18)
at Object.fs.readFileSync (fs.js:551:33)
at Object.<anonymous> (/Users/jennielin/index11.js:3:11)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
Your program tried to look for a private key file (privkey.pem) in the /etc/letsencrypt/live/awiclass.monoame.com directory. It could not find the file, and since there was no error handling done in the case that the file isn't found, it crashed.
You can fix this by adding a privkey.pem file to that directory.
Im trying to run this simple code but I m getting error all the time...I really dont know what's the problem. It seems to me very Ok...? Thanks!
var http = require(http);
console.log('Starting');
var host = '127.0.0.1';
var port = 1337;
var server = http.createServer(function(request, response){
console.log('Receive request: '+ request.url);
response.writeHead(200, {"Content-type" : "text/plain"});
response.end("Hello world");
});
server.listen(port, host, function(){
console.log('Listening: ' + host + ':' + port);
});
Console error is this:
assert.js:98
throw new assert.AssertionError({
^
AssertionError: path must be a string: path must be a string
at Module.require (module.js:362:3)
at require (module.js:380:17)
at Object.<anonymous> (/Users/yoniPacheko/PhpstormProjects/angularJS/nodeJS/server.js:9:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
In your first line there are quotes missing around http:
var http = require('http');
In my case, I had
var http = require('http');
var path= require('path');
As soon as I deleted the the http line, it worked for me.So, i did leave only
var path= require('path');
I was working on express,mongodb,socket.io.
I am following a tutorial on how to set up a basic mvc in Nodejs using the hapi server and a few other packages.
Tutorial: https://www.sitepoint.com/node-js-mvc-application/
Git for my project: https://github.com/christoph88/node-js-mvc-tut/
I have an error when I try to launch the server:
~/Projects/node-js-mvc-tut$ node server.js
/home/christoph/Projects/node-js-mvc-tut/server.js:33
Models.sequelize.sync().then(() => {
^
TypeError: Cannot read property 'sync' of undefined
at Object.<anonymous> (/home/christoph/Projects/node-js-mvc-tut/server.js:33:17)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
Model is defined within the requirements. I do not understand why sync is undefined. Sequelise is required within the lib/index.js file.
'use strict';
const Hapi = require('hapi');
const Hoek = require('hoek');
const Path = require('path');
const Settings = require('./settings');
const Routes = require('./lib/routes');
const Models = require('./lib/models/');
const server = new Hapi.Server();
server.connection({ port: Settings.port });
server.register([
require('vision'),
require('inert')
], (err) => {
Hoek.assert(!err, err);
server.views({
engines: { pug: require('pug') },
path: Path.join(__dirname, 'lib/views'),
compileOptions: {
pretty: false
},
isCached: Settings.env === 'production'
});
// Add routes
server.route(Routes);
});
Models.sequelize.sync().then(() => {
server.start((err) => {
Hoek.assert(!err, err);
console.log(`Server running at: ${server.info.uri}`);
});
});
Can somebody help me with this? Would be great to get this running so I can try to adapt it to my needs.
I have got it working by moving my index.js file to the models folder.
This file has the necessairy scripts that dispatches sequelise in the model thus fixing the problem.
Make sure you have exported the db in index.js
module.exports = db
and declared a db variable at the beginning of the file
var db = {}