I have following Application structure
/routes
- index.js
dbconfig.js
dbresources.js
server.js
1. Content of /routes/index.js
exports.index = function(req, res){
console.log("Routes Successfully");
sequelize.query("SELECT * FROM users_tbl").success(function(rows) {
res.format({
json: function() {
res.send(rows);
}
});
// res.jsonp(rows);
}).error(function(error) {
console.log(error);
});
};
2. Content of dbresources.js
module.exports = {
database: {
name: "dbproject",
host: "root",
password: ""
}
}
3. Content of dbconfig.js
var Sequelize = require('sequelize')
, mysql = require('mysql');
config = require("./dbresources");
db = config.database;
var sequelize = new Sequelize(db.name, db.host, db.password, {
dialect: 'mysql'
});
4. Content of server.js
var express = require('express')
, http = require('http')
, app = express()
, http = require('http')
, routes = require('./routes')
, path = require('path');
app.configure(function() {
app.set('port', process.env.PORT || 5000);
app.use(express.bodyParser());
app.set(express.methodOverride());
app.set(express.router);
app.use(express.static(__dirname + '/src'));
});
app.get('/user', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log("\n\n\tNode (Express) server listening on port " + app.get('port'))
});
When i am running my apps using node and fire localhost:5000/user. It shows me following error.
ReferenceError: sequelize is not defined
The error is exactly what's wrong. You're using sequelize without defining it first it in /routes/index.js. If it's the var you've created in dbconfig, you first need to expose it like so:
// The rest of the code...
exports.sequelize = sequelize;
and import it in /routes/index.js like so:
var sequelize = require('./dbconfig').sequelize;
// The rest of the code...
Related
I am a newbie in node.I have created a server file to connect mongoDB and wrote routes in the same. Created a model.js for table attributes.I want to write a route for my other tables.
https://codingthesmartway.com/the-mern-stack-tutorial-building-a-react-crud-application-from-start-to-finish-part-2/
Taken reference from here. But want to create a seperate file for connection and add module for tables
This is my server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
app.use('/todos', todoRoutes);
mongoose.connect('mongodb://127.0.0.1:27017/todos', {
useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established
successfully");
})
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
this routes are in this file i want to export it from other model.js
If you want to put route in another file,i would suggest you to make a new folder route and then inside it make a new file by route name(say createUser.js).
In this server.js file only use
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = 4000;
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
app.use('/todos', todoRoutes);
mongoose.connect('mongodb://127.0.0.1:27017/todos', {
useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established
successfully");
})
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
export default app;
And in another file inside route folder use the require imports and define the route here.
const todoRoutes = express.Router();
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
module.exports=todoRoute;
Furthur you can import this route in any model.js and use it for implementation of logic.
Note-: You can also use a third folder controllers and implement the route logic there since it is the best practice to not write logic on route but use controller file for it.Also you can separate the DB connection login in another file.
I have used below code. i have run the file and there are no errors. But the server 192.123.1.134:5001 shows 'No data received'.
Kindly help me to find out error in the code.
express = require('express');
app = express();
config = require('./config/database.js');
var path = require('path');
//app.set('views', __dirname + '/views')
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
router = express.Router();
var routes = require('./user/index');
var admin = require('./user/user');
app.use('/', routes);
app.use('/user', admin);
http = require('http');
server = http.createServer(app);
server.listen('5001','192.123.1.134', function(){
console.log('%s: Node server started on %s:%d ...',Date(Date.now() ));
});
index.js
var User = require('../model/user.js');
router.get('/', function(req, res, next) {
User.getuserdetails(function(data) {
res.render('user', {
title: 'Welcome',
result : data
});
});
//res.render('index', { title: 'welcome' });
});
module.exports = router;
user.js (model)
var connection =require("../config/database.js");;
router.getuserdetails = function (req,res){
var result = connection.query('SELECT * FROM table1','', function (err, rows) {
if (err) throw err
});
}
module.exports = router;
database.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'aaa',
database : 'my_db'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Just give the localhost/127.0.0.1 in the IP address part.
You can access it in LAN using your IP address 192.123.1.134.
server.listen('5001','127.0.0.1', function(){
console.log('%s: Node server started on %s:%d ...',Date(Date.now() ));
});
Smarter programmers, please advise:
two variables coming in from an AJAX post (username, pic)
get them at the route users.js from req.body
have my functions in a file main.Funcs exported to server.js
I can't figure out how to get the variables out of my route and into my server.js, so that I can use them with my functions. Can't figure out how to do it without circular 'require' between routes and mainFuncs.
QUESTIONS:
How do you access variables from routes without (1) making global variables, nor (2) circular require between routes and mainFuncs?
Could set global variables but bad? Some way to call them in a big function that gives access to scope without making global?
server.js
var express = require('express');
var mainFuncs = require('./mainFunctions.js');
mainFuncs.startServer();
mainFuncs.sqlConnectionCheck();
mainFuncs.learnFace(username, picLink);
mainFuncs.js
const client = some api methods, input from route --> api --> json back
var express = require('express');
var users = require('./routes/users');
var bodyParser = require('body-parser');
app.use('/users', users);
var app = express();
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(express.static('public'));
app.use('/', main);
app.use('/users', users);
app.use('/profile', profile);
var mainFuncs = {
startServer: function () {
app.listen(3000, function() {
models.users.sync({ force: true });
models.userPicData.sync({ force: true });
console.log('Listening on port 3000!');
});
},
sqlConnectionCheck: function (){
sequelize
.authenticate()
.then(function(err) {
console.log('Connection to mysql: success.');
})
.catch(function (err) {
console.log('Connection to mysql: failed with these errors: ', err);
});
},
learnFace: function (username, picPath) {
client.faces.detect({ urls: picPath, attributes: 'all' })
.then(function(result){
var newLearn = JSON.parse(result);
var newTid = newLearn.photos[0].tags[0].tid;
var fullNameSpace = username + '#notARealNameSpace';
console.log('You have been registered with the name: ' + username);
client.tags.save(newTid, fullNameSpace, {label: nameString, password: 'optionalPassword'});
client.faces.train(nameString, { namespace: 'urface' });
})
},
};
module.exports = mainFuncs;
routes/users.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var app = express();
router.post('/create', function(req,res){
var username = req.body.username;
var picLink = req.body.pic;
});
module.exports = router;
Typically express apps are structured so that the Business Logic, Routes and Express server are in separate locations. The actual logic to your app goes inside a directory /lib. Your routes go inside /routes and your server.js goes into your project root.
/<root>
/lib
/public
/routes
server.js
package.json
Do you mean my mainFuncs should be imported into the router? It just seems like I'm writing most of the program in the routes at that point?
No, your logic goes into separate files inside /lib and your /routes will require it when necessary. This approach is decoupled and allows your logic to live outside of your routes. The logic may be implemented in multiple routes if necessary yet be centralized and easy to maintain. This leaves your routes free to only implement the code needed to determine the response and update session state.
The above code could be structured as so:
server.js
const express = require('express');
const bodyParser = require('body-parser');
const users = require('./routes/users');
// Place DB and any other initialization here in server.js
// so it will be guaranteed to execute prior to the server listening
const app = express();
const port = process.env.PORT || 1337;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use('/users', users);
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
module.exports = app;
/lib/learnFace.js
const client = require('<package>'); // Some package etc per your question
function learnFace(username, picPath) {
return client.faces.detect({ urls: picPath, attributes: 'all' })
.then(function(result){
let newLearn = JSON.parse(result);
let newTid = newLearn.photos[0].tags[0].tid;
let fullNameSpace = username + '#notARealNameSpace';
console.log('You have been registered with the name: ' + username);
client.tags.save(newTid, fullNameSpace, {label: nameString, password: 'optionalPassword'});
client.faces.train(nameString, { namespace: 'urface' });
});
}
module.exports = learnFace;
/routes/users.js
const router = require('express').Router();
const learnFace = require('../lib/learnFace');
router.post('/create', (req, res) => {
let username = req.body.username;
let picLink = req.body.pic;
return learnFace(username, picLink)
.then(() => {
return res.sendStatus(201);
})
.catch((err) => {
return res.sendStatus(500);
})
});
module.exports = router;
Also you don't need to require Express in every file like you are no need to, only require the things you need in files that you are using.
I am working on app which uses node, express, mysql on server side. i have written serveral APIs on server.js file and when i am trying to access those using Postman then req.body is always undefined.
this is my server.js configuration.
var express = require('express');
var mysql = require('mysql');
var cors = require('cors');
var bodyParser = require('body-parser');
var wrench = require("wrench");
var fs = require('fs');
var path = require("path");
var mkdirp = require('mkdirp');
var walk = require('walk');
var fse = require('fs-extra');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var crypto = require('crypto');
app.use(cors());
app.use(bodyParser.urlencoded({limit: '50mb',extended: false}));
app.use(bodyParser.json({limit: '50mb'}));
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'dbname'
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
app.post('/urlreq', function(req, res){
console.log(req.body);
}
app.listen(3000, function(){
console.log("Rest Demo Listening on port 3000");
});
When i am trying send something in body in Postman then req.body is coming empty on server side.
If you are sending multipart/form-data, it doesn't work because bodyparser doesn't handle this body type.
In this case adding the following line should fix it:
app.use(multipartMiddleware);
Form the docs:
multipart/form-data is the default encoding a web form uses to transfer data
Try add:
var express = require('express');
var app = express();
[...]
// Last stack
app.listen(3000, function(){
console.log("Rest Demo Listening on port 3000");
});
You can use as a middleware also. Also listen on a port. add following lines in your code -
var app = express();
app.use(function(req, res, next) {
console.log('Current User:', req.body);
next();
});
app.post('/url', function(req,res){
console.log(req.body)
});
app.listen(3000, function(){
console.log('Express server listening on port 3000');
});
I believe I have socket.io setup properly in the main file (server.js) of an Express app. How do I access socket.io from a controller to emit an event as part of a controller action?
I tried the following based on a similar post, but I am getting an error saying that socket is not defined. Any help will be greatly appreciated.
Similar post:
Socket.io emit from Express controllers
server.js:
'use strict';
var express = require('express'),
path = require('path'),
fs = require('fs'),
mongoose = require('mongoose'),
http = require('http'),
socketio = require('socket.io');
/**
* Main application file
*/
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = require('./lib/config/config');
var db = mongoose.connect(config.mongo.uri, config.mongo.options);
// Bootstrap models
var modelsPath = path.join(__dirname, 'lib/models');
fs.readdirSync(modelsPath).forEach(function (file) {
if (/(.*)\.(js$|coffee$)/.test(file)) {
require(modelsPath + '/' + file);
}
});
// Populate empty DB with sample data
require('./lib/config/dummydata');
// Passport Configuration
var passport = require('./lib/config/passport');
// Setup Express
var app = express();
// Setup socket.io
var server = http.createServer(app);
var io = socketio.listen(server);
require('./lib/config/express')(app);
require('./lib/routes')(app);
// Start server
// Call listen on server instead of app to setup socket.io. See this post:
// https://stackoverflow.com/questions/21173182/why-isnt-my-angularjs-express-socket-io-app-serving-the-socket-io-js-file/21175137#21175137
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %s:%d, in %s mode', config.ip, config.port, app.get('env'));
});
io.sockets.on('connection', function(socket) {
console.log('socket connected');
socket.emit('message', {
message: 'You are connected to the backend through the socket!'
});
});
// Expose app
exports = module.exports = app;
routes.js:
'use strict';
var api = require('./controllers/api'),
index = require('./controllers'),
users = require('./controllers/users'),
items = require('./controllers/items'),
session = require('./controllers/session'),
middleware = require('./middleware');
/**
* Application routes
*/
module.exports = function(app, socket) {
app.route('/api/items')
.get(items.index)
.post(items.create(socket));
// All undefined api routes should return a 404
app.route('/api/*')
.get(function(req, res) {
res.send(404);
});
// All other routes to use Angular routing in app/scripts/app.js
app.route('/partials/*')
.get(index.partials);
app.route('/*')
.get( middleware.setUserCookie, index.index);
};
items.js (controller):
'use strict';
var mongoose = require('mongoose'),
Item = mongoose.model('Item');
exports.create = function(socket) {
return function(req, res) {
// write body of api request to mongodb
socket.emit();
}
}