I am facing this error in my Expressjs file . Here is my code. I tried to set it according to this link
https://github.com/expressjs/multer/issues/169 But I am unable to correct this. Kindly help me out.
/**
* Express configuration
*/
'use strict';
var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var multer = require('multer');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
module.exports = function(app) {
// var env = app.get('env');
var env = 'development';
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(compression());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(multer({
dest: '../client/assets/images/uploads/',
rename: function(fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting...');
},
onFileUploadComplete: function(file, req, res) {
console.log(file.fieldname + ' uploaded to ' + file.path);
var fileimage = file.name;
req.middlewareStorage = {
fileimage: fileimage
}
}
}));
app.use(cookieParser());
app.use(passport.initialize());
// Persist sessions with mongoStore
// We need to enable sessions for passport twitter because its an oauth 1.0 strategy
app.use(session({
secret: config.secrets.session,
resave: true,
saveUninitialized: true,
store: new mongoStore({
mongooseConnection: mongoose.connection
})
}));
if ('production' === env) {
app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
app.use(express.static(path.join(config.root, 'public')));
app.set('appPath', config.root + '/public');
app.use(morgan('dev'));
}
if ('development' === env || 'test' === env) {
// app.use(require('connect-livereload')());
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(path.join(config.root, 'client')));
app.set('appPath', 'client');
app.use(morgan('dev'));
app.use(errorHandler()); // Error handler - has to be last
}
};
check your multer version as there was a syntax change in how to use multer.
now you have to define something as follows
var upload = multer({.....})
then use upload as your middleware in the express route.
Related
I am using Socket.io for real time image upload process but I got this error mentioned below. I'm writing socket and app.js logics in different files by referring this answer now i want to emit that socket events in controller files but got the error
UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function
below is my code
app.js
// modules =================================================
var express = require('express');
var app = express();
const logger = require('morgan');
var bodyParser = require('body-parser');
const indexRouter = require("./routes/index");
const cors = require('cors');
const path = require("path");
const config = require("./environments/index");
var http = require('http').Server(app);
var sockets = require('./apis/socket.io');
// configuration ===========================================
var port = config.PORT || 8081; // set our port
sockets.getSocketIo(http);
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
}));
app.use(cors());
app.use(logger('dev'))
app.use("/api", indexRouter);
app.use(express.static(path.join(__dirname, "/build")));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(port, () => {
console.log('Magic happens on port ' + port); // shoutout to the user
});
exports = module.exports = app;
This is socket.io.js file code
var socketio = require('socket.io');
var io = {};
module.exports = {
getSocketIo: function (app) {
let userId = 1
io = socketio.listen(app);
io.sockets.on('connection', function (socket) {
console.log("new connection: " + socket.id);
console.log(socket)
console.log('socket connected')
// let rooms = socket.id
io.sockets.adapter.rooms
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" +
userId].length > 0) userId++;
socket.join("room-" + userId);
//Send this event to everyone in the room.
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
io.sockets.in(userId).emit('Image_upload', "Image uploading is started");
console.log(socket.room)
console.log(socket)
});
}
};
This is controller code of api controller
report_data: async (req, res) => {
if (!req.body.id) {
logger.warn(error.MANDATORY_FIELDS);
return res.status(500).send(error.MANDATORY_FIELDS)
}
io.emit('progress', "Image is Uploading started Please Wait A minute");
io.emit('error', "clients connected!");
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
req.body.data_url = path
sequelize.sequelize.transaction(async (t1) => {
let result = error.OK
result.data = data
logger.info(result);
return res.status(200).send(result)
}).catch(function (err) {
logger.warn(err);
console.log(err)
return res.status(500).send(error.SERVER_ERROR)
})
},
You can Make changes like below in your file
app.js
// modules =================================================
var express = require('express');
var app = express();
const logger = require('morgan');
var bodyParser = require('body-parser');
const cors = require('cors');
const path = require("path");
const config = require("./environments/index");
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
const indexRouter = require("./routes/index");
// configuration ===========================================
var port = config.PORT || 8081; // set our port
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
}));
app.use(cors());
app.use(logger('dev'))
app.use("/api", indexRouter);
app.use(express.static(path.join(__dirname, "/build")));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(port, () => {
console.log('Magic happens on port ' + port); // shoutout to the user
});
app.locals.io = io
exports = module.exports = app;
socket.io.js
let io;
const getSocketIo = (http) => {
let userId = 1
io = require('socket.io')(http);
io.sockets.on('connection', function (socket) {
io.sockets.adapter.rooms
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" + userId].length > 0) userId++;
socket.join("room-" + userId);
//Send this event to everyone in the room.
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
console.log("new connection: " + socket.id);
console.log('socket connected')
});
}
module.exports = {
getSocketIo,
io
};
in your controllers add this code in api you have mentioned whenever you want to use socket add this code before using it
const io = req.app.locals.io;
During setup of nodejs(as backend, port: 3333), and vuejs(frontend, port: 8080) environment, I was unable to access 'GET /article'. Also, when I remove connect-history-api-fallback, all I can see is json formatted database data.
How can I fix this?
Below is the code for app.js:
var express = require('express');
var app = express();
var history = require('connect-history-api-fallback');
app.use(history({
index: '/index.html',
verbose: true
}));
app.use(express.static(path.join(__dirname, 'public')));
// app.use(bodyParser.json());
var IndexRouter = require('./routes/index');
var ArticleRouter = require('./routes/article');
app.use('/', IndexRouter);
app.use('/article', ArticleRouter);
Below is the code for routes/article.js:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function (req, res) {
console.log('article get 접근하였습니다.');
pool.getConnection(function (err, connection) {
if (err) {
throw error;
}
const sqlQuery = 'SELECT * from board_article';
connection.query(sqlQuery, function (err, rows) {
if (err) {
connection.release();
throw error;
} else {
res.json(rows);
connection.release();
}
});
});
});
I'm trying to build a small nodejs, express, mongodb app with authentication using passport-local and passport-local-mongoose, however for some reason when entering the middleware for passport in the main app.js file I get this error "TypeError: User.authenticate is not a function"
I tried the authentication by itself in a test project and it worked just fine, so maybe it's something to do with the order of my code but I can't get to what's causing this issue. I've tried several refactors but to no avail.
Below is the code for the app.js and the User Schema , but Here's a link to the project files if needed.
app.js
const express = require('express'),
app = express(),
path = require('path'),
exphbs = require('express-handlebars'),
methodOverride = require('method-override'),
flash = require('connect-flash'),
session = require('express-session'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
LocalStrategy = require("passport-local"),
passport = require("passport"),
mongodb = require("mongodb"),
User = require("./models/User");
// Load routes
const ideas = require('./routes/ideas');
const users = require('./routes/users');
// Connect to mongoose
mongoose.connect('mongodb://localhost/diaries');
mongoose.Promise = Promise;
// Handlebars Middleware
app.engine('handlebars', exphbs({
defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Static folder
app.use(express.static(path.join(__dirname, 'public')));
// Method override middleware
app.use(methodOverride('_method'));
// Express session midleware
//PASSPORT CONFIGURATION
app.use(require("express-session")({
secret: "secret",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(flash());
// Global variables
app.use(function(req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
// Index Route
app.get('/', (req, res) => {
const title = 'Welcome';
res.render('index', {
title: title
});
});
// About Route
app.get('/about', (req, res) => {
res.render('about');
});
// Use routes
app.use('/ideas', ideas);
app.use('/users', users);
const port = process.env.PORT;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
User Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require("passport-local-mongoose");
// Create Schema
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
password:{
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
UserSchema.plugin(passportLocalMongoose, {usernameField: "email"});
mongoose.model('users', UserSchema);
try importing LocalStrategy from require('passport-local').Strategy
like
const LocalStrategy = require('passport-local').Strategy
I'm following this Thinkster tutorial on building a reddit-esque web app using MEAN.
The tutorial instructs using curl to create a new post.
C:\root>curl --data "title=test&link=http://test.com" http://localhost:3000/posts
However, I get this error in response:
<h1>Not Found</h1>
<h2>404</h2>
<pre>Error: Not Found
at C:\root\app.js:30:13
at Layer.handle [as handle_request] (C:\root\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\root\node_modules\express\lib\router\index.js:312:13)
at C:\root\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\root\node_modules\express\lib\router\index.js:330:12)
at next (C:\root\node_modules\express\lib\router\index.js:271:10)
at C:\root\node_modules\express\lib\router\index.js:618:15
at next (C:\root\node_modules\express\lib\router\index.js:256:14)
at Function.handle (C:\root\node_modules\express\lib\router\index.js:176:3)
at router (C:\root\node_modules\express\lib\router\index.js:46:12)</pre>
I looked through those files, but all the references were just showing me what happens to the error...
Here's some code
/routes/index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
router.get('/posts', function(req, res, next){
Post.find(function(err,posts){
if(err){ return next(err); }
res.json(posts);
})
})
router.post('/posts', function(req,res,next){
var post = new Post(req.body);
post.save(function(err, post){
if(err){ return next(err); }
res.json(post);
})
})
/models/Posts.js:
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {type: Number, default: 0},
comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}]
});
mongoose.model('Post', PostSchema);
app.js:
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 index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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('/', index);
app.use('/users', users);
// 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 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;
var mongoose = require('mongoose');
require('./models/Posts');
require('./models/Comments');
mongoose.connect('mongod:localhost/news');
I feel like I did everything correct, except I wasn't sure where to place the additional routes in the routes index file, and similarly in app.js. But this seems negligible to me. I performed all the debugging I could think of but am stuck.
It should also be noted that this tutorial was perhaps not intended for use on a Windows machine. I had to install curl and do a few other things that perhaps wouldn't be necessary on a Linux or Mac. I am using Windows 10.
Your module.exports is called prematurely in routes/index.js. Move module.exports = router; to the bottom of your file, recycle your service, and try again.
Also there are issues with app.js. See below:
app.js:
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');
// Notice the differences starting here
var app = express();
var mongoose = require('mongoose');
// connect MongoDB
mongoose.connect('mongodb://localhost/news', function(err,db){
if (!err){
console.log('Connected to /news!');
} else{
console.dir(err); //failed to connect
}
});
require('./models/Posts');
require('./models/Comments');
var index = require('./routes/index');
var users = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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('/', index);
app.use('/users', users);
// 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 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;
routes/index.js:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/posts', function(req, res, next){
Post.find(function(err,posts){
if(err){
alert(err);
return next(err);
}
res.json(posts);
})
})
router.post('/posts', function(req,res,next){
var post = new Post(req.body);
post.save(function(err, post){
if(err){
alert(err);
return next(err);
}
res.json(post);
})
})
module.exports = router;
I don't understand why my deserialize method is being called so many times. Here's my server.js file
var express = require('express');
var app = express();
var passport = require('passport');
var bodyParser = require('body-parser');
var session = require('express-session');
var MongoSessionStore = require('connect-mongo/es5')(session);
// Local ENV ======================================================================
var env = require('./config/config.json')[app.get('env')];
// Mongo Database ======================================================================
var mongoInstance = require('./config/db.config.js');
mongoInstance.connection.on('open', function(){
console.log('connection works');
});
// Configuration ======================================================================
app.use(session({
secret: 'secretsarenofun', // Change this to anything else
resave: false,
saveUninitialized: true,
store: new MongoSessionStore({
mongooseConnection: mongoInstance.connection,
autoRemoveInterval: 60
})
}));
require('./config/passport.config.js')(passport, env, mongoInstance);
app.use(passport.initialize());
app.use(passport.session());
// Routes ======================================================================
var auth = require('./routes/auth.route')(app, passport);
var users = require('./routes/users.route')(passport);
// Middleware ======================================================================
app.use(express.static(__dirname + '/public'));
app.use('/users', users);
app.use('/auth', auth);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Launch ======================================================================
var server = app.listen(8000, function(){
console.log('The dagger flies at 8000');
});
var io = require('socket.io').listen(server);
require('./sockets')(io);
And in my passport module I set this
module.exports = function(passport, env, db){
var request = require('request');
var OpenIDStrategy = require('passport-openid').Strategy;
var steamKey = 'test';
var User = require('../models/user.model');
var SteamStrategy = new OpenIDStrategy({
providerURL: 'http://steamcommunity.com/openid',
stateless: true,
returnURL: env.path+'/auth/openid/return',
realm: env.path,
},
function(identifier, done) {
var steamId = identifier.match(/\d+$/)[0];
return done(null, {
identifier: identifier,
steamId: identifier.match(/\d+$/)[0]
});
});
passport.use(SteamStrategy);
passport.serializeUser(function(user, done) {
done(null, user.identifier.match(/\d+$/)[0]);
});
// used to deserialize the user
passport.deserializeUser(function(identifier, done) {
console.log('this calls too many times');
//fetch
done(null, identifier);
});
};
When I just visit the home page after I have auth'd the deserialize function calls like it's supposed to but it's calling up to 8 times.
Why is this? I tried moving the app.use(passport.initialize());
app.use(passport.session()); around with some luck but not completely. Why does this occur?
Move app.use(express.static(__dirname + '/public')) above app.use(passport.initialize());