I need to set some common global variables in one config file and will get those values where required using Node.js. Here I need to implement process.env. My code is below:
var port=8989;
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var session = require('express-session');
var multer = require('multer')
var app=module.exports=express();
var server=http.Server(app);
var admin=require('./route/route.js');
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT
app.use(session({secret: 'FGDPlexel',resave: true,saveUninitialized: true}));
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
})
var storage =multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
server.listen(port);
console.log("Server is running on the port"+port);
Here I am assigning port=8989 but here I need to create one config file and will assign all variable there. In this server.js that file will include and user will get the required values.
You can use the dotenv npm package. It requires you to setup an .env file with key-value pairs in the format KEY=VALUE like SECRET_KEY=MEGASECRETKEY.
const dotenv = require('dotenv');
dotenv.load({
path: '.env.globals' // example
});
and you can access your variables like process.env.SECRET_KEY
It is not very clear for me what you are specifically asking for, but for configuration purposes, you can create your own config.js file and require it.
For instance;
var settings = {
port: process.env.PORT
};
module.exports = settings;
Then at your server.js, you can require this file.
var settings = require('./config.js');
Related
I am trying to upload a single image using python code to a node js express server. The python code is:
import requests
url = 'http://localhost:9000/testAPI/uploadphoto'
files = {'file': ('photo', open('test.jpg', 'rb'))}
ret = requests.post(url, files=files)
print ret
For the app.js, it is mostly following the default template:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser= require('body-parser')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require("./routes/testAPI");
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
//app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({extended: true}))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/testAPI", testAPIRouter);
// 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 I am using the router testAPI for handling the POST:
var express = require('express');
var multer = require('multer');
var router = express.Router();
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads')
},
filename: function (req, file, cb) {
var filename = file.originalname;
var fileExtension = filename.split(".")[1];
cb(null, Date.now() + "_" + filename);
}
});
var upload = multer({ storage: storage });
router.get('/', function(req, res, next) {
console.log("test");
res.send('API is working properly');
});
router.post('/uploadphoto', upload.single('photo', (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send('Photo uploaded');
}));
module.exports = router;
When I run the python code, the server returns 500. In my node js directory, I have an uploads folder created.
At the first you should run your node server project in port 9000
Your npm start probably calls your bin/www file. Which contains the listen invocation to start your app.
Many people set up their app this way. eg. app.js to define and configure their app, and something like bin/www to actual get the server running. This way they can include the app.js into other parts, say tests, without actually starting the server when you require it.
Figured it out. Since my server is started in the bin/www file as opposed to the app.js file, from the terminal I went into my bin directory and then called
node wwww
or
nodemon www
or add this code to the app.js and then run it with node app.js to listen port 9000
const port = 9000;
app.listen(port, () => console.log(Example app listening on port ${port}!))
I am using express-fileupload to parse the body of my request and access any files that are sent with the request. This works fine when I am trying to do this locally but when I push it to heroku, the files are not being parsed - instead req.files is null. My code is below:
Parsing middleware:
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
module.exports = function (app) {
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileUpload()); // EXPRESS-FILEUPLOAD BEING USED HERE
};
Routes file:
router.post('/photo', function(req, res, next) {
console.log("INSIDE OF THE ROUTE =======>>>>>");
const userId = req.body.userId;
const busketName = 'my-bucket-name';
let newPhotosArray = [];
var busboy = new Busboy({ headers: req.headers });
req.pipe(busboy);
busboy.on('finish', function() {
const filesObj = req.files;
console.log('FILES OBJ: ', filesObj); // THIS IS LOGGED OUT AS NULL ON HEROKU - LOCALLY IT IS AN OBJECT WITH FILES
// rest of code....
});
});
The code works great when I use it locally. However, when I push the code to Heroku, req.files is null. Why is this?
I am writing a simple MEAN app, and I am currently working on the routes.
In my server.js, I have
var express = require('express');
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
var sizeOf = require('image-size');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
require('./app/models/Purchase');
require('./app/models/Seller');
require('./app/models/User');
// config files
var db = require('./config/db');
var port = process.env.PORT || 8080; // set our port
// mongoose.connect(db.url); // connect to our mongoDB database
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
// routes ==================================================
var routes = require('./app/routes/routes');//(app); // pass our application into our routes
var price = require('./app/routes/pricing');
var processing = require('./app/routes/processing');
var uploads = require('./app/routes/uploads');
var seller = require('./app/routes/seller');
app.use('/', routes);
app.use('/price', price);
app.use('/processing', processing);
app.use('/uploads', uploads);
app.use('/seller', seller);
// start app ===============================================
app.listen(port);
console.log('Magic happens on port ' + port);
exports = module.exports = app;
Then, in my route, I have
var express = require('express');
var mongoose = require('mongoose');
var Seller = mongoose.model('Seller');
var router = express.Router();
router.get('/', function(req,res){
res.json({message: 'youre in router.get'});
});
router.post('/registerSeller', function(req,res,next){
console.log('You made it all the way to seller route!');
res.json({message: "you did it"});
next();
});
module.exports = router;
When I start my node server, everything goes well. When I use Postman to POST to the above route, it just 'hangs' and eventually gives an error message that it cannot connect. In Postman, I select 'POST' to http://localhost:8080/seller/registerSeller.Clicking 'code', I get
POST /seller/registerSeller HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
Postman-Token: 070cb9b3-992a-ffd6-cede-c5b609bc9ce5
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Looking at the browser's developer tools, it shows a POST being made, and then after a while, it also reads that the POST failed.
Could anyone tell me what I'm doing wrong? Thank you.
The problem is that you are responding and then trying to call the next() function in the router stack.
router.post('/registerSeller', function(req,res,next){
console.log('You made it all the way to seller route!');
return res.send({message: "you did it"});
//next(); remove this shit.
});
This should work. Express middlewares go in order. So if you need to have a middleware to be called before this function, then you have to put it before in the stack. If you need to do something after this function, forget about the res.json... part.
New to Express App , I am trying to setup mongodb using express and node.js. I have some issues if i can get some help in this area. i tried to add directories refrences so you can have idea.
1- var config is coming undefined not sure path is correct.
2- getting SyntaxError: Unexpected reserved word for
require('./config/express')(app);.
Basically trying to have app running with local mongodb.
server > app.js
var express = require('express');
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var config = require('./config/environment');
var http = require('http');
var https = require('https');
var fs = require('fs');
var bodyParser = require('body-parser');
// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
console.error('MongoDB connection error: ' + err);
process.exit(-1);
});
// Setup server
var app = express();
var server = http.createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Start server
function startServer() {
server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
}
setImmediate(startServer);
// Expose app
exports = module.exports = app;
server > config > express.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var path = require('path');
var config = require('./config/environment');
var session = require('express-session');
var connectMongo = require('connect-mongo');
var mongoose = require('mongoose');
var mongoStore = connectMongo(session);
export default function(app) {
var env = app.get('env');
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.set('appPath', path.join(config.root, 'client'));
if ('development' === env || 'test' === env) {
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(app.get('appPath')));
app.use(morgan('dev'));
server > config > environment > development.js
module.exports = {
// MongoDB connection options
mongo: {
uri: 'mongodb://localhost/test-modeler-dev'
},
// Seed database on startup
seedDB: false
};
As it was pointed out in the comments of the question, your problem is that you are using newer JavaScript features with an older version of Node. To get around the current error, you should change this line in server > config > express.js:
// ...
export default function(app) {
// ...
To
// ...
module.exports = function(app) {
// ...
This should solve this particular problem. But if the code you are using is using other features of ECMAScript 2015 that aren't supported by your version of Node, then you have two options:
Update to the latest version of Node.js here.
Refactor all of your code remove all ECMAScript 2015 features to ensure that it works with your version of Node.js.
Hope this helps.
I'm currently writing a web application with the MEAN stack, and am testing to see if my nodejs server is working. Here's my server.js:
// server.js
'use strict';
// modules =================================================
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
// expose app
exports = module.exports = app;
I currently have it redirecting all routes to my index.html file to test to make sure my views are working. Here's my routes.js:
// models/routes.js
// grab the user model
var User = require('./models/user.js');
module.exports = {
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
However, when I try to run node server.js, it gives me this error:
/home/hess/Projects/FitTrak/app/routes.js
app.get('*', function(req, res) {
^
SyntaxError: Unexpected token .
Does anyone have any idea what's causing this? I checked and all my braces and parentheses are all closed and written correctly.
As Jose Hermosilla Rodrigo said in his comment, you're declaring the object literal module.exports wrong. It should look like this instead:
module.exports = function(app) {
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
just try this code...
// models/routes.js
var express=require('express');
var app=express();
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
module.exports = route;
server.js
'use strict';
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var route=require('./models/route.js');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
app.use('/',route);
If you are using MEAN stack I would suggest you to use express own router middleware to handle all your routes. Just include.
var router = express.Router();
//use router to handle all your request
router.get(/xxx,function(req, res){
res.send(/xxxx);
})
// You may have n number of router for all your request
//And at last all you have to do is export router
module.exports = router;