I'm trying to make my vocabulary app using and changing MDN node/express tutorial.
MDN tutorial works perfectly but mines doesn't work.
Here are the errors :
Error: Route.post() requires a callback function but got a [object String]
at Route.(anonymous function) [as post] (d:\web-projects\vocastudy\node_modules\express\lib\router\route.js:202:15)
at Function.proto.(anonymous function) [as post] (d:\web-projects\vocastudy\node_modules\express\lib\router\index.js:510:19)
at Object.<anonymous> (d:\web-projects\vocastudy\routes\catalog.js:9:8)
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 Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (d:\web-projects\vocastudy\app.js:9:21)
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)
And app.js :
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var catalogRouter = require('./routes/catalog');
var app = express();
// Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://127.0.0.1/vocastudy';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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('/', indexRouter);
app.use('/users', usersRouter);
app.use('/catalog', catalogRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// 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');
});
module.exports = app;
And my routes catalog.js :
var express = require('express');
var router = express.Router();
var vocabulary_controller = require('../controllers/vocabularyController');
// GET request for creating a Word. NOTE This must come before routes tha display Word (uses id).
router.get('/create', vocabulary_controller.create_get);
/* POST create page */
router.post('/create', vocabulary_controller.create_post);
/* GET home page. */
router.get('/', vocabulary_controller.list);
/* GET detail page */
router.get('/:id', vocabulary_controller.detail);
module.exports = router;
And controllers vocabulary.js :
exports.create_post = [
// Validate fields
body('word').isLength({ min: 1 }).trim().withMessage('word must be specified'),
body('meaning').isLength({ min: 1 }).trim().withMessage('meaning must be specified'),
body('reference').isLength({ min: 1 }).trim().withMessage('reference must be specified'),
// Sanitize (trim and escape) the fields
sanitizeBody('word').trim().escape(),
sanitizeBody('meaning').trim().escape(),
sanitizeBody('reference').trim(),escape(),
// Process request after validation and sanitization
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
// Create vocabulary object with escaped and trimmed data.
if(!errors.isEmpty()) {
// There are errors.
res.render('create', { title: 'Create Word', word: req.body, errors: errors.array() });
return;
} else {
// Data from form is valid.
// Create a Vocabulary object with escaped and trimmed data.
var vocabulary = new Vocabulary({
word: req.body.word,
meaning: req.body.meaning,
reference: req.body.reference
});
vocabulary.save(function(err) {
if(err) { return next(err); };
// Successful - redirect to new word record.
res.redirect(vocabulary.url);
});
};
}
];
I think that create post controller is array so I got error but it perfectly works on MDN's tutorial version. I can't find my problem.
why did i get route.post error?
NB that mdn's tutorial is using array too.
It seems that in Express, app.post() accepts parameters that can be arrays of callbacks, but router.post() only accepts functions as callbacks. Try providing the array directly to an express app instead of the router, or as #TimothyLee suggested, use the spread syntax to turn the array into individual parameters to the router.post() function.
Related
enter image description here
here's the app.js(--please find attached image):
//here's the app.js
const express = require("express");
const app = express();
app.use(express.json());
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
const authJwt = require("./helpers/jwt");
const errorHandler = require("./helpers/error-handler");
app.use(cors());
app.options('*', cors());
//middleware
app.use(morgan("tiny"));
app.use(authJwt());
app.use(errorHandler()); //-> **this isn't correct?**
//Importing routing of products
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const req = require("express/lib/request");
const res = require("express/lib/response");
const api = process.env.API_URL;
//routers
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/orders`, ordersRoutes);
app.use(`${api}/users`, usersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewurlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("database connection is ready");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("Server is Running http://http://localhost:3000");
});
//error image
//here's the error handler code
function errorHandler(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
}
module.exports = errorHandler;
> Blockquote (--please find attached image)
here's the error
C:\Users\steve\Backend\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\steve\Backend\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\steve\Backend\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981: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
Your error handler function is correct, but the problem is that you're calling the function instead of passing it directly to your express app.
Remove the parenthesis after the errorHandler and it should work.
app.use(errorHandler); // Don't call errorHandler, express will call it
Think of it like this.
if I just call errorHandler() in any context it won't return anything.
That means that errorHandler() evaluates to undefined.
Now in your code, when you do app.use(errorHandler()) instead of evaluating to the following:
app.use(function(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
});
Your code is actually evaluating to
app.use(undefined);
and so express is throwing an error because undefined is not a function.
I tried making a project on my own and this error happened. I couldn't fix it. It just somehow happens and I am so confused where to start looking for the error.
app.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminData = require('./routes/admin');
const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminData.routes);
app.use(shopRoutes);
app.use((req, res, next) => {
res.status(404).render('404', { pageTitle: 'Page Not Found' });
});
app.listen(3000);
admin.js
const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const router = express.Router();
const products = [];
// /admin/add-product => GET
router.get('/add-product', (req, res, next) => {
res.render('add-product', {
pageTitle: 'Add Product',
path: '/admin/add-product',
formsCSS: true,
productCSS: true,
activeAddProduct: true
});
});
// /admin/add-product => POST
router.post('/add-product', (req, res, next) => {
products.push({ title: req.body.title });
res.redirect('/');
});
exports.routes = router;
exports.products = products;
shop.js
code snippet of shop.js
This is my error.
I am making a webpage for the first time using this.
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'body-parser'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\User\Documents\My Website\05-working-on-layout-with-partials\app.js:4:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
[nodemon] app crashed - waiting for file changes before starting...
Please try to install the required body-parser module,
Use following command to do so.
npm install body-parser
Please install the dependency i.e body-parser
npm i body-parser --save
Error is on the 4th line of app.js its not getting the body-parser module
I am getting an error when calling my router from my routes directory.I have made some changes in my code around some of the other posts on this issue but I can't get anything to solve.However i am not sure what exactly is wrong with my code below.
This is my error
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
E:\Program Files\mean apps\shoppinglist\crud-backend\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 (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\app.js:42:5)
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 Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:279:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:752:3)
[nodemon] app crashed - waiting for file changes before starting...
I have this code in my app.js
//importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//conect to the mongodb
mongoose.connect('mongodb://localhost:27017/shoppinglist');
//on connection
mongoose.connection.on('connected',()=>{
console.log('Connected to database mongodb # 27017');
});
//error
mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('Error in database connection:'+ err);
}
});
//port no
const port = 3000;
//adding middleware - cors
app.use(cors());
//body - parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname, 'public')));
//routes
app.use('/api', route);
//testing server
app.get('/',(req, res)=>{
res.send('foobar');
});
app.listen(port,()=>{
console.log('Server started at port:' + port);
});
I have this code in my route.js
const express = require('express');
const router = express.Router();
const Item = require('../model/shoppingItem');
//retriving data from db
router.get('/items', (req, res, next)=>{
Item.find(function(err, items){
if(err){
res.json(err);
}
else{
res.json(items);
}
});
});
//insert data
router.post('item', (req, res, next)=>{
let newShoppingItem = new Item({
itemName: req.body.itemName,
itemQuantity: req.body.itemQuantity,
itemBought: req.body.itemBought
});
newShoppingItem.save((err, item)=>{
if(err){
res.json(err);
}
else{
res.json({msg: 'Item has been added successfully'});
}
});
});
You are using a module that you never exported.
app.use('/api', route);
but route was never exported - that's your main issue.
in your route module you can wrap everything in export default - alternatively you can use module.exports = router
This is an open source project I was working on try following the structure, if you still have issues let me know.
https://github.com/Muhand/nodejs-server
My goal is to connect my server code that its with nodejs and expressjs framework to my database that is with orientdb.
first of all i wanted to store my sessions in database. but i had difficulty connecting my server to database.
the error that i get when i execute server.js:
/Users/soroush/Desktop/nodeOrient/node_modules/connect-orientdb/lib/connect-orientdb.coffee:191
})(connect.session.Store);
^
TypeError: Cannot read property 'Store' of undefined
at module.exports (/Users/soroush/Desktop/nodeOrient/node_modules/connect-orientdb/lib/connect-orientdb.coffee:22:46)
at Object.<anonymous> (/Users/soroush/Desktop/nodeOrient/server.js:8:48)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:449:3
and my server.js code is:
var express = require('express'),
cs = require("coffee-script/register"),
app = express(),
path = require('path'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
config = require('./config/config.js'),
orientDBStore = require('connect-orientdb')(session),
OrientDB = require('orientjs'),
orientDBConfig = {
server : {
host: "localhost",
port:2424
},
db : {
user_name: "admin",
user_password: "admin"
},
database : "sessions",
class_name : "sessions_class"
},
server = OrientDB({
hose : "localhost",
port : "2424",
username : "root",
password : "root"
})
;
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname,'public' )));
app.use(cookieParser());
require('./routes/route.js')(express, app);
app.use(session({
secret:"mySecret",
store: new orientDBStore(orientDBConfig)
}));
app.listen(8000, function () {
console.log("app is listening on port 8000");
})
my main problem is that the connect-orientdb was used when the session module was builtin in express, but now that session is a different module i have occurred to this problem.
Check out this guide for ExpressJS in OrientDB: Blog Tutorial with ExpressJS and OrientDB.
And try to use:
orientDBStore = require('orient')(session),
instead of:
orientDBStore = require('connect-orientdb')(session),
Finally i found a solution for it if anyone faced this problem:
var session = require('express-session'),
OrientoStore = require('connect-oriento')(session);
app.use(session({
secret: 'SomeSecret',
store: new OrientoStore({
server: "host=localhost&port=2424&username=dev&password=dev&db=test"
})
}));
for more info this github link is useful.
I recently implemented socket.io and running into some strange errors.
The error messages I am getting aren't incredibly helpful and trying to figure out what is causing this.
Here are the contents of my app.js -
app.js
// Express Requirements
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
// Formidable Requirements
var formidable = require('formidable');
var util = require('util');
var routes = require('./routes/index');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8888);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// Non Default Code
// Socket.io Code
io.on('connection', function (client) {
console.log("Client connected!");
client.emit('newcommer',{status: true, newuser: 'paul'});
});
// End Socket.io Code
// End Non Default Code
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Error Message
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Object.<anonymous> (/Users/blah/blah/app.js:20:8)
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 Module.require (module.js:364:17)
28 Nov 19:10:39 - [nodemon] app crashed - waiting for file changes before starting...
Does anyone see anything that is off that could be causing this error?
Edits For Culprits:
Once these lines are removed then the code does not produce any errors:
var server = require('http').Server(app);
var io = require('socket.io')(server);
// Socket.io Code
io.on('connection', function (client) {
console.log("Client connected!");
client.emit('newcommer',{status: true, newuser: 'paul'});
});
// End Socket.io Code
Are you sure, you are getting this error ???
I think you have another server running on the same port server.listen(8888);
Either close that running server or changer the port as server.listen(8000);