form.parse() never called, when i delete bodyparser then it, my session variable throughs error , how to make it work
logcat
write(string, encoding, offset, length) is deprecated. Use
write(string[, offset[, length]][, encoding]) instead. events.js:85
throw er; // Unhandled 'error' event ^ Error: ENOENT, open
'/home/pitu/CODING/NODE-PROJECTS/chichat/files/a88b7a4fbd8cb31e276ef60c8e934d2d.png'
at Error (native)
app.js file
var express = require('express'),
app = express(),
http = require('http'),
path = require('path'),
fs = require('fs'),
mysql = require('mysql'),
server = http.createServer(app),
//events = require('events'),
//path = require('path'),
//url = require('url'),
//Create a new store in memory for the Express sessions
sessionStore = new express.session.MemoryStore(),
passport = require('passport'),
flash = require('connect-flash'),
useragent = require('express-useragent'),
cookieParser = express.cookieParser('hjnjnm'),
io = require('socket.io').listen(server);
// configuration ===============================================================
// connect to our database
require('./config/passport')(passport); // pass passport for configuration
app.configure(function() {
// set up our express application
app.use(express.logger('dev')); // log every request to the console
app.use(cookieParser); // read cookies (needed for auth)
app.use(useragent.express());
app.use(express.methodOverride());
app.use(express.bodyParser({keepExtensions:true,uploadDir:path.join(__dirname,'/files')}));
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(express.session({store: sessionStore,key: 'myuser.sid',cookie: { secure: false,maxAge:3600000}} )); // session secret1
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(path.join(__dirname, 'public')));
app.all('*', function(req, res, next)
{
res.header("Access-Control-Allow-Origin", "*");
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
});
require('./app/socket/mainSocket.js')(app,io,sessionStore,cookieParser);
// routes ======================================================================
require('./app/controller.js')(app, passport,io); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
server.listen(8080);
what should i use, bodyparser or formidable, i want to upload big file to server, which one will suit my need with minimum overhead.
any help will be appreciated, thank you
[1]: https://stackoverflow.com/a/25016730/2254638 it solved my issue,happy coding , :)
Related
I have tried to install the NPM packages from the cpanel. But when I try to open the website, I get the response incomplete response received from application. When i run it offline, it works properly, but when i move it to the cpanel, it gives me the incomplete response error
var express = require("express"),
app = express(),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
session = require("express-session"),
methodOverride = require("method-override"),
nodemailer = require("nodemailer"),
multer = require("multer"),
dotenv = require("dotenv").config(),
Product = require("./models/products"),
User = require("./models/user");
var mongoDB = process.env.MONGODB_URL;
mongoose.connect(mongoDB, { useNewUrlParser: true , useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var indexRoutes = require("./routes/index"),
storeRoutes = require("./routes/products");
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
//User Passport Config
app.use(require("express-session")({
secret: process.env.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(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();
});
app.use(indexRoutes);
app.use("/store", storeRoutes);
app.use(function(req, res){
res.send ("Error finding page")
})
const port = process.env.PORT;
app.listen (port, function(){
console.log ("Server Active");
});
this is what i saw in the the .htaccess file. I only placed some passwords and other private info in the .env file
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php70” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php70 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN
PassengerAppRoot "/home/zenitcou/zenitcouture"
PassengerBaseURI "/"
PassengerNodejs "/home/zenitcou/nodevenv/zenitcouture/11/bin/node"
PassengerAppType node
PassengerStartupFile app.js
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN
<IfModule Litespeed>
</IfModule>
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END
Share the response you are getting, that we can help you better
From the configuration provided, I can't tell the exact cause but I may have enough experience why you end up getting "incomplete response received from the application".
The error message might be confusing, but what it really wants to say is, nothing is actually sent from your app upon HTTP request is sent by the proxy aka. Phusion Passenger.
You can read more about what are those Passenger config in their docs
but my gist is one of these:
Your app is maybe crashed due to improper configuration. I suggest using PassengerAppEnv development to track error messages.
Phusion passenger integration on Node.JS is somewhat magic, they just don't care what app.listen port you're giving on. But it probably crashes because you set them undefined. Please set a fallback on your PORT env like const port = process.env.PORT || 80;
You set PassengerStartupFile as app.js. Is it true? (People usually set their main entry file as server.js. You have to make sure the file exists.
I faced the same error.
For me, it was log4js. The process.send() function was undefined.
By disabling the clustering of log4js, all become fine.
To find where the error is, I proceeded with code reduction. Compiling a few lines of codes
May it helps someone
When I run my Express.js application with node app.js everything works as expected, including this example route:
router.get('/config/get', function(req, res, next) {
return res.json("hi");
});
However, when I build my docker image and run it, my browsers shows me my index page on this route. In fact, it shows my index page at pretty much every single route, nomatter if I set it up or not. So when I go to /this/route/is/non-existing/ I see my index page as well. This only works through docker. When I visit this page by running the node application without docker, I get a 404.
Be aware that I use connect-history-api-fallback for my vue.js frontend. My app.js looks like this:
require('dotenv').config()
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 history = require('connect-history-api-fallback');
var app = express();
// history mode for making vue.js router work: https://router.vuejs.org/guide/essentials/history-mode.html
app.use(history());
history({
index: '/dist/index.html'
});
// 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('/', indexRouter);
// serving vue.js prod build
app.use(express.static('dist'));
// 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;
app.listen(process.env.PORT, () => console.log(`${process.env.NAME} listening on port ${process.env.PORT}!`))
This is my Dockerfile:
FROM node:10
# Create app directory
WORKDIR /usr/src/app
# use non-root user to run commands and give him chown permissions for the directory
USER node
COPY --chown=node:node ./backend .
EXPOSE 8080
CMD [ "node", "app.js" ]
I am building a REST API using NodeJS and Express, powered by a MongoDB database.
I've been struggling for days now trying to get the right folder structure nailed down. So far, I can connect to my database and add new users without an API, but by simply doing GET, POST, etc. requests. I've seen several tutorials online on how to build API using node, but none of them have a more standardized way for setting their folder structure. And that is the reason why I am having such a hard time making it work given my current folder structure.
Here is my Folder Structure
app
---models
------user.js
---api.js
---routes.js
config
---auth.js
---database.js
---passport.js
public
views
package.json
server.js
Server.js
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 2016;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
app.configure(function() {
// set up our express application
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.set('views', path.join(__dirname + '/views'));
app.set('view engine', 'ejs'); // set up ejs for templating
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// required for passport
app.use(express.session({ secret: 'xxxxxxxxx' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
});
// routes ======================================================================
// require('./app/routes')(app, passport); // load our routes and pass in our app and fully configured passport
// require('./app/api')(api, passport);
app.use('/', require('./app/routes')(app, passport));
app.use('/api', require('./app/api')(api, passport));
// error handlers
// Catch unauthorised errors
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401);
res.json({"message" : err.name + ": " + err.message});
}
next();
});
// launch ======================================================================
app.listen(port);
console.log('Live on port ' + port);
api.js
var User = require('./models/user');
var express = require('express');
var apiRoutes = express.Router();
app.use('/api', apiRoutes);
module.exports = function(apiRoutes, passport){
apiRoutes.get('/testapi', function (req,res) {
res.json({SecretData: 'abc123'});
});
}
Every time I hit the endpoint /testapi I get the error "Cannot GET /testapi"
I think my main issue is how to organize my files and folder properly and import/require them the right way. Can anyone help me figure this out?
Server.js
on this line app.use('/api', require('./app/api')(api, passport));
Here you are telling Express to use ./app/api as an middleware by passing "api" and "passport" as arguments.
where you have defined api variable ?
Lets assume its a typo.. in that case from "app/api.js" you are exporting a function and you trying to execute it in server.js app.use('/api', require('./app/api')(api, passport)); which returns undefined.
Express will be expecting a function as middleware not a return value from function.
app/api.js
on line 4 you have app.use('/api', apiRoutes); which doesn't make any sense, because api.js has no idea about "app".
Cleanup your server.js and api.js and try again
This tutorial might help Node with Express
I get typeError: object is not a function
when I run:
node server.js
for the following line of code
require('./app/routes.js')(app, passport);
from the following code for my server.js file:
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
// configuration ================================================================
mongoose.connect(configDB.url); // connect to our database
// require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get info from html forms
app.use(bodyParser.urlencoded({ extended: true}));
app.set('view engine', 'ejs'); // set up ejs for templating
// requirements for passport:
app.use(session({ secret: 'ilovescotchscotchyscotchscotch'}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ========================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch =======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
not entirely sure why this is happening...
I was following this tutorial btw: https://scotch.io/tutorials/easy-node-authentication-setup-and-local
Thanks!
Based on your comments: this post does a pretty good job of explaining how require works in nodeJS (it's not a Javascript thing). Basically every file that can be required is generally expected to export something that the requiring file can assign to a variable (e.g. var someVar = require('someFile');). IF the exported value is a function then you can immediately invoke it before assigning to that variable (e.g. var someVar = require('someFile')(params);). For your error it appears that the file ./app/routes.js is not exporting a function.
FILE: ./app/routes.js
// some code that does cool stuff
// ...
// Time to expose whatever we want to the requiring file
module.exports = someObject; // Or value, function, etc.
FILE: main.js
// we want cool stuff from routes.js
var coolStuff = require('./app/routes.js');
// someObject from ./app/routes.js is now assigned to coolStuff
coolStuff(); // ERROR: object is not a function
console.log(typeof coolStuff) // "object"
I've seen many variations of this question, but none seemed to solve my issue. I'm trying to set up a Node.js server using Express. Here is my server configuration:
var express = require('express'),
RedisStore = require('connect-redis')(express);
var app = express();
app.use(express.urlencoded());
app.use(express.json());
app.use(express.cookieParser());
app.use(express.session({
store: new RedisStore(),
secret: APP_SECRET
}));
// Initialize redis connection
var client = redis.createClient();
client.on('connect', function() {
console.log('Connected to Redis server')
})
client.on('error', function (err) {
console.log('Error ' + err);
});
// Enable cross-origin resource sharing
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
});
var api = require('./controllers/api.js');
app.post('/login', api.login);
app.get('/auth', api.auth);
app.listen(3000);
And here are some simple routes:
exports.login = function(req, res) {
var user = new User(req.username, req.password);
req.session.user = user;
console.log(req.session.user); //works
res.json({user:user});
}
exports.auth = function(req, res) {
console.log(req.session.user); //doesn't work
res.json(req.session.user);
}
So in my login route, I can print the session variable as expected. But if I visit the auth route after visiting the login route, the session variable is undefined. How can I get Express sessions to work?
In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.
Each subsequent request will not contain credentials or all user data, but rather the unique cookie that identifies the session. In order to support login sessions, You have to serialize and deserialize user instances to and from the session in every request.
In your case, you have assigned req.session.user = user; only in /login request. It will not be available for further requests(/auth).
You have to get user information in /auth request too by session id. (Or) Better you can use passport for authentication.
I think maybe your redis client is not connecting well, try something like this and be sure to start the redis service
sudo service redis-server start
or the way you are calling The RedisStore variable look at the example
example:
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.set('port',process.env.PORT || 3000);
app.use(cookieParser());
app.use(session({
resave: true,
saveUninitialized: true,
store: new RedisStore({
host: 'localhost',
port: 6379
}),
secret: 'some string/hash secret'
}));
var counter=0;
app.get('/', function(request, response){
//adding some value to request.session
counter = counter+1;
request.session.color = {'anyValue': counter};
//
console.log('Session ID: ', request.sessionID);
console.log('Session: ', request.session);
response.send('some text counter: '+request.session.color['anyValue']);
});
app.listen(app.get('port'));
The currently accepted answer didn't realize that express.session already handles cookie based sessions with the req.session object. I tried a trimmed down version of yours not using redis and it worked. Looking at the connect-redis docs it looks like you need to pass a session to connect-redis. You are currently passing it express. I believe changing that will fix your problem.
P.S. I would update your node/express versions as current versions of express no longer have the built in middleware along with other improvements.
Newer versions of express:
var session = require('express-session');
var cookieParser = require('cookie-parser');
var json = require('express-json');
var bodyParser = require('body-parser')
Rather than:
express.session
express.cookieParser
express.json
express.bodyParser