I have issue setting up routes for user in below code, I want to use express middleware and trying routes using app.use.
index.js is invoking user controller method once api's is being called So in below code i am trying to post data api/users from client but it returns 404.
How can i fix this issue using below routes setup ?
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
var db = require('./config/db');
var port = process.env.PORT || 8080;
mongoose.connect(db.url);
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // configure our routes
require('./config/express')(app);
app.listen(port);
console.log('listening on port ' + port);
exports = module.exports = app;
app > routes.js
module.exports = function(app) {
app.use('api/users', require('./api/user'));
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
// res.sendFile(path.join(__dirname, ''../public/views/index.html''));
});
};
config > express.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
// import cookieParser from 'cookie-parser';
// import errorHandler from 'errorhandler';
var path = require('path');
// import lusca from 'lusca';
var config = require('./db');
var mongoose = require('mongoose');
//var mongoStore = connectMongo(session);
module.exports = function(app) {
// app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
}
User index where i will handle all crud operation for user
app > api > user > index.js
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
router.get('/', controller.index);
router.post('/',controller.create);
module.exports = router;
1st:
To handle all request
Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
app.use(function(req,res)
{
res.sendfile('./public/views/index.html');
console.log("Not found....I will handle *unhandle* rout here for you");
})
// app.get('*', function(req, res) use the above function instead of this
But this function at the end so it will only excute when no route path found to the app object.
Express documentation
2nd:
To handle createuser
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
// you must define route which you want to handle in user file
router.get('/api/user', controller.index);
router.post('/',controller.create);
module.exports = router;
Update working example with some explanation
Your app.js file
var express=require('express')
var app=express()
app.use('api/user',require('./user'))
app.use('/',require('./user'))
app.use(function(req,res)
{
res.sendfile('stack10.html')
console.log("Not found....I will handle *unhandle* rout here for you");
})
app.listen(8080,function()
{
console.log("server listening on port 8080")
})
user.js
var express = require('express')
var router = express.Router()
var app=express()
router.get('/api/user', function(req, res) {
res.send('respond for ..../api/user')
});
router.get('/',function (req,res) {
res.send('respose for ..../')
})
module.exports = router;
Your app.use will be app.use(api/user) while in user will be router.get(/api/user) so when u try http://127.0.0.1:8080/api/user
your response will be respond for ..../api/user
Related
when i run this , i should be able to get mysite at localhost:3000 . but when i go to localhost:3000 it is not loading. chrome is still showing waiting for localhost. This is the code . It is a simple node js blog that uses mongo db. I got it from this github https://github.com/pankajwp/node-js-blog
This is the code for server. Please help
i will add my mongodb credentials to mongoose.connect.
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var expressLayouts = require('express-ejs-layouts');
var mongoose = require('mongoose');
mongoose.connect('');
var Schema = mongoose.Schema;
app.use('/assests',express.static(__dirname + '/public'));
app.use(expressLayouts);
app.use((req, res, next) => {
res.locals.baseUrl = req.baseUrl;
next();
});
// by default express will look for static files inside the filder called views
app.set('view engine', 'ejs');
// Controllers
var pageController = require('./controllers/pageController');
var postController = require('./controllers/postController');
var adminController = require('./controllers/adminController');
var randomController = require('./controllers/randomController');
randomController(app);
adminController(app, Schema, mongoose);
postController(app, Schema, mongoose);
pageController(app, Schema, mongoose);
// Listen
app.listen(port);
console.log('Listening on localhost:'+ port);
Following thing is wrong
// Listen
app.listen(port);
console.log('Listening on localhost:'+ port);
Right away after calling listen, app does not listen immediately to the specified port.
The code should be like following
app.listen(port, function() {
console.log(`Listening on localhost: ${port}!`);
})
What is happening here, listening to a port is a asynchronous task. It is accepting some callback to let you know, what is the status of your listening to the port. If successful, then callback is called.
What your code was doing is, whether the listening to port is success of not, it always prints Listening on localhost: xxxx.
Example taken from directly Express Hello world.
Try This:
const express = require('express');
const ejs = require('ejs');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 3000;
//Create Object like this
const Schema = new mongoose.Schema({
//your properties name goes here like:
name: {
type:String
}
});
app.use('/assests',express.static(__dirname + '/public'));
app.use(expressLayouts);
app.use((req, res, next) => {
res.locals.baseUrl = req.baseUrl;
next();
});
// by default express will look for static files inside the filder called views
app.set('view engine', 'ejs');
// Controllers
var pageController = require('./controllers/pageController');
var postController = require('./controllers/postController');
var adminController = require('./controllers/adminController');
var randomController = require('./controllers/randomController');
randomController(app);
adminController(app, Schema, mongoose);
postController(app, Schema, mongoose);
pageController(app, Schema, mongoose);
//db connection
mongoose
.connect('url goes here, ({useUnifiedTopology: true, useNewUrlParser:true}))
.then(() => console.log('MongoDB connected!!!'))
.catch(err => console.log(err));
app.listen(port, (req, res) => console.log(`Server is running at ${port}`));
you can try with adding this code jsut after declaring your port number.
app.use(bodyParser.json());
your updated code should looks like below and it should work on http://localhost:3000
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
var expressLayouts = require('express-ejs-layouts');
var mongoose = require('mongoose');
mongoose.connect('');
var Schema = mongoose.Schema;
app.use('/assests',express.static(__dirname + '/public'));
app.use(expressLayouts);
app.use((req, res, next) => {
res.locals.baseUrl = req.baseUrl;
next();
});
// by default express will look for static files inside the filder called views
app.set('view engine', 'ejs');
// Controllers
var pageController = require('./controllers/pageController');
var postController = require('./controllers/postController');
var adminController = require('./controllers/adminController');
var randomController = require('./controllers/randomController');
randomController(app);
adminController(app, Schema, mongoose);
postController(app, Schema, mongoose);
pageController(app, Schema, mongoose);
// Listen
app.listen(port);
console.log('Listening on localhost:'+ port);
This is my home.js code
// import 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');
//port no
const port =3000
app.use(cors());
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname,'public')));
app.use('./api', route);
//testing server
app.get('/', (req,res)=>{
res.send('foober');
})
app.listen(port,()=>{
console.log('server started at port:' + port);
});
And this the route.js code
const express = require('express');
const router = express.Router();
router.get('/contacts', (req, res, next )=>{
res.send('retrieve contact');
});
module.exports =router;
But whenever I run 'localhost:3000/api/contacts' i get 'Cannot GET /api/contacts' error. I am very new at this, what am I doing wrong?
A dot in an url is there to seperate domains, if your route is mounted at ./api you would have to visit yourserver.com./api which won't work as the url is invalid.
I have a simple nodejs app with some users. I want to load a specific user profile using a URL localhost/users/(username) but I'm getting this error when I try to load the URL:
Cannot GET /users/test
Here's my user.js routes file for the user page:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
// GET user by username
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.send(req.params);
res.render('user');
});
module.exports = router;
I have a user.handlebars file in my views folder so it should load the file. What am I missing in my routes file? Any help would be greatly appreciated. Thanks!!
EDIT: app.js:
console.log('Starting app.js');
const fs = require('fs');
const _ = require('lodash');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tipcup');
var db = mongoose.connection;
const routes = require('./routes/index');
const users = require('./routes/users');
const user = require('./routes/user');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// BodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport Init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator ({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
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');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/users/:username', user);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Render function renders a view and sends the rendered HTML string to the client.Take a look at documentation.
But what you are trying to archive is to send data first and then render and send again. So, just delete the line with send.
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.render('user');
});
And, please, edit your question by adding your code with middleware and add your error.
Update
Take a look at the way how you define your routes for users.
You have to remove /users from defining route in users.js file
js and i am learning node js along with express and I was learning express routing I have following code in rest.js
const http = require('http');
const express = require('express');
const widgetRouter = require('./rest/widgets');
const app1 = express();
const server = http.createServer(app1);
app1.get('/api',widgetRouter);
server.listen(3000,function(){
console.log('server started in port 3000');
});
const app = express();
and I also have widgets.js file
const express = require('express');
const widgetRouter = express.Router();
widgetRouter.route("/widgets")
.get(function(req,res){
res.json({"abc":"hello"});
})
.post();
widgetRouter.route("/widgets/:widgetId")
.get()
.put()
.delete();
module.exports = widgetRouter;
but When I try to test the rest api(http://localhost:3000/api/widgets) from postman it says Cannot GET /api/widgets
You have imported and initialized the express module, but then you start a server with the http module. You should use only Express:
Also you should use app.use('/api',widgetRouter) instead of app.get('/api', widgetRouter) which is an express middleware.
const express = require('express');
const app = express();
const widgetRouter = require('./rest/widgets');
app.use('/api', widgetRouter);
app.get('/', function(req, res) {
res.send('Home');
});
app.listen(3000, function(){
console.log('server started in port 3000');
});
You can also try that.
rest.js
const express = require('express');
const http = require('http');
const router = express.Router();
const app = express();
require('./widgets')(app, router);
app.get('/', function(req, res) {
res.send('Home');
});
app.listen(3000,function(){
console.log('server started in port 3000');
});
widgets.js
module.exports = function(app, router){
router.route("/widgets")
.get(function(req,res){
res.json({"abc":"hello"});
})
.post();
router.route("/widgets/:widgetId")
.get()
.put()
.delete();
app.use('/api', router);
});
I'm a beginner in node.js but I try a little harder to setup a structure in node + express js.I start doing with the front-end and separate API structure.I put a single app.js for both API and front-end.But my API is not working. it gives error Cannot GET /api/users when i call http://localhost:3000/api/users. please help
api
-controllers
-helpers
-middlewares
-models
-routes.js
app.js
controllers
helpers
middlewares
models
node_modules
package.json
public
views
app.js
var express = require('express')
, app = express()
, bodyParser = require('body-parser')
, port = process.env.PORT || 3000
var path = require('path');
app.set('views', path.join(__dirname, 'views/'));
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(require('./controllers'))
var routes = require('./api/routes');
app.use('/api', routes);
app.listen(port, function() {
console.log('Listening on port ' + port)
})
routes.js
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
module.exports = function (app) {
app.get('/users', usersController.getUser);
};
module.exports = router;
users.js(controller)
module.exports = {
getUser: function (req, res) {
console.log("sdfdsfdsfsd");
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({"msg": "welcome user"}));
}
}
In your routes.js file you are exporting two things. Try to only export the router
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
router.get('/users', usersController.getUser);
module.exports = router;