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 = {}
Related
I have a modular based js Frontend. It only contains nodemon and express packages. I currently have src elements within my index.html, which point to my js modules. Or at least I believe that src elements are properly acquiring my files, I could be wrong. Here is a code snippet.
<script src="../index.js"></script>
<script src="../src/ingredient/ingredient.js"></script>
<script src="../src/ingredient/ingredientService.js"></script>
<script src="../src/user/user.js"></script>
<script src="../src/user/userService.js"></script>
<script src="../src/category/category.js"></script>
<script src="../src/category/categoryService.js"></script>
<script src="../src/project/project.js"></script>
<script src="../src/project/projectService.js"></script>
Within my index.js, I am attempting to initialize class objects. My current setup does not allow index.js to acquire outside modules and I cannot figure out why. Do I need another package like webpack to bundle it all together or perhaps its an issue with my code? Here is the error
const ingredientService = new IngredientService(base_url)
^
ReferenceError: IngredientService is not defined
at Object.<anonymous> (/Users/jasondavis/Flatiron/code/ProjitekFrontEnd/index.js:14:29)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
INDEX.JS
const express = require('express');
const app = express();
const port = 3001;
app.use(express.static('public'));
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
//USING NODEMON.JS
const base_url = "http://localhost:3000/api/v1"
//NEED TO ACQUIRE CLASS MODULE INSIDE SRC DIR
const ingredientService = new IngredientService(base_url)
const categoryService = new CategoryService(base_url)
const projectService = new ProjectService(base_url)
const deleteBttn = document.querySelector("deleteProject")
Ingredient.ingredientForm.addEventListener('submit', submitIngredient)
Project.projectForm.addEventListener('submit', submitProject)
Project.editProjectForm.addEventListener('submit', updateProject)
Project.testForm.addEventListener('submit', submitTest)
categoryService.getCategories()
ingredientService.getIngredients()
projectService.getProjects()
function showProject(){
event.preventDefault()
projectService.showProject()
}
function submitIngredient(){
ingredientService.createIngredient()
}
function submitProject(event){
projectService.createProject()
}
function updateProject(event){
projectService.backEndedit()
}
function submitTest(event){
event.preventDefault()
Project.submitTest()
}
function updateIngredient(event){
ingredientService.backEndedit()
}
document.addEventListener('DOMContentLoaded', () => {
Project.scrollAble()
})
What I am able to do so far: Render index.html and index.js contents to DOM
GITHUB REPO: https://github.com/jasonronalddavis/ProjitekFrontEnd
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 have added routes to post-event data.
var keystone = require('keystone');
var Event = keystone.list('Event');
module.exports = function (req, res) {
if (!req.body.name || !req.body.startTime || !req.body.endTime) {
return res.send({ status: 'incomplete data set' });
}
var newEvent = new Event.model();
Event.updateItem(newEvent, req.body, function (error) {
res.locals.enquirySubmitted = true;
if (error) res.locals.saveError = true;
res.render('addEvent');
});
};
When I start the app I am getting below error.
if (!result) throw new ReferenceError('Unknown keystone list ' + JSON.stringify(key));
^
ReferenceError: Unknown keystone list "Events"
at Keystone.list (/Users/rigalpatel/KS_shopingcart/node_modules/keystone/lib/core/list.js:7:21)
at Object. (/Users/rigalpatel/KS_shopingcart/routes/api/event/post.js:2:22)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at /Users/rigalpatel/KS_shopingcart/node_modules/keystone/lib/core/importer.js:42:23
at Array.forEach ()
at importer (/Users/rigalpatel/KS_shopingcart/node_modules/keystone/lib/core/importer.js:32:26)
at /Users/rigalpatel/KS_shopingcart/node_modules/keystone/lib/core/importer.js:36:22
at Array.forEach ()
Would you please provide your feedback. suggestion how to fix above issue.
Vesrion
Keystone 4.0.0
Node.js 10.9.0
Browser Google Chrome 69.0.3497.100
Thanks
I had this error and realized I was setting my routes before importing my models. Make sure you are importing your models before setting your routes and that your models are registered.
error comes because you have not created any Model with name Event
I had a perfectly working relay modern app with 1.1.0 babel-plugin-relay + react-relay + react-compiler + graphql 0.10.x, react 15.5.x but since upgrading all of them to 1.4.1 and graphql to 0.11.7 and react to 16.0.0 I keep getting this error when running npm start:
ERROR in ./src/main.js
Module build failed: Error: BabelPluginRelay: Expected plugin context to include "types", but got:[object Object]
at BabelPluginRelay (/Users/johndoe/testing/atc/node_modules/babel-plugin-relay/lib/BabelPluginRelay.js:36:11)
at Object.<anonymous> (/Users/johndoe/testing/atc/src/babelRelayPlugin.js:28:18)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at /Users/johndoe/testing/atc/node_modules/babel-core/lib/transformation/file/options/option-manager.js:178:20
# multi (webpack)-dev-server/client?http://localhost:3333 ./src/main.js
webpack: Failed to compile.
with babel-plugin-relay like so:
babelRelayPlugin.js:
const babelRelayPlugin = require('babel-plugin-relay')
const { introspectionQuery, buildClientSchema, printSchema } = require('graphql/utilities')
const request = require('sync-request')
const fs = require('fs')
const path = require('path')
const schemaPath = path.join(__dirname, 'schema');
const graphqlHubUrl = 'https://myhub.com/dev/graphql'
const response = request('POST', graphqlHubUrl, {
qs: {
query: introspectionQuery
}
})
console.log('response ', response)
const schema = JSON.parse(response.body.toString('utf-8'))
console.log('schema ', schema)
const graphQLSchema = buildClientSchema(schema.data);
fs.writeFileSync(
`${schemaPath}.graphql`,
printSchema(graphQLSchema)
);
module.exports = babelRelayPlugin(schema.data, {
abortOnError: true
})
and webpack.config.js:
query: {
presets: ['env', 'react', 'stage-2'],
plugins: ['relay', 'transform-class-properties', __dirname + '/src/babelRelayPlugin']
}
the question is why ? and how I can fix it? because in the response I can clearly see types:
Solved it.
Had to change this:
module.exports = babelRelayPlugin(schema.data, {
abortOnError: true
})
to this:
module.exports = babelRelayPlugin(schema.data.__schema, {
abortOnError: true
})
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.