Working with express Router for getting for the first time.
This is my route.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('home page');
});
module.exports = router;
This is my index.js
var express = require('express');
var app = express();
var router=require('./route.js');
app.use('/route',router);
var server = app.listen(process.env.PORT ||8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
});
When I open run it in browser it shows:
Cannot GET /
The only URL the code you have written will respond to is:
www.example.com/route/
If you want it to respond to:
www.example.com
then change to the following in your index.js file:
app.use('/', router);
You should replace
app.use('/route',router); with app.use('/', router);
As I may see you have created default route in app.use as /route
you must not have added that using app.use('/') would be enough instead of creating another route for that
Thanks.
Related
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.
Ok so I'm trying to redirect the request to a different controller depending on the URL.
My server.js :
const express = require('express');
var app = express();
var router = express.Router();
// controllers
var { loginController } = require('./controller/loginController');
// Specify routes
app.use('/test', loginController);
app.listen(3000, () => {
console.log('started on port 3000');
});
module.exports = { app }
Now if the URL is /test then I would like to redirect the request to loginController, inside loginController I have the following:
const express = require('express');
var router = express.Router();
router.get('/', (req, res) => {
res.send('inside logincontroller');
});
Very short and sweet, however when I run node server.js I get the following error message: Router.use() requires middleware function but got a undefined now I've gone through the Router Use but I'm slightly confused (newbie) I don't have any middleware at present.
Would someone be able to explain to me how I go about redirecting the request to the loginController when the url is /test
server.js
const express = require('express')
// Controllers
var loginController = require('./controller/loginController')
var app = express()
// Specify routes
app.use('/test', loginController)
app.listen(3000, () => {
console.log('started on port 3000')
})
loginController.js
const express = require('express')
var router = express.Router()
router.get('/', (req, res) => {
res.send('inside logincontroller')
})
module.exports = router
Then if you visit http://localhost:3000/test will get the output 'inside logincontroller'
I want to export my routes in external files.
Everything but the root route is working:
localhost/login -> "Login page"
localhost/ -> empty
server.js:
// SET UP =============
var express = require("express");
var app = express();
var port = 80;
var bodyParser = require("body-parser");
// CONFIG =============
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// ROUTES =============
var base = require("./routes/base");
app.use("/",base);
// LISTEN =============
app.listen(port);
console.log("Server listening on port " + port);
base.js:
var express = require('express')
var router = express.Router()
//Home
router.get('/', function (req, res) {
res.send('Home page')
})
//Login
router.get('/login', function (req, res) {
res.send('Login page')
})
module.exports = router
You don't need to specify the route on app.use('/', base) instead just supply the router middleware directly to your express app and let the router within base handle the request.
app.use(base)
Uhm, okay I found my problem.
There is an empty index.html in my ./public folder.
You're overwriting the root route with your /login route and only exporting the /login one because of that. If you want to keep all routes in one file I recommend doing something in you base.js file like:
module.exports = function(server){
server.get('/', function(request, response){
response.send('Home page.');
});
server.get('/login', function(request, response){
response.send('Login page.');
});
}
Then in the server.js file import the route using:
require('./routes/base.js')(app);
This immediately imports the routes and calls their functionality on the Express server you crated :)
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
very new to nodejs here. I've tried to put routes in app.js without problem. However, after moving all the routes to a separate file under PROJECT_DIR/src/routes/index.js, and then I open the page in browser it says "Cannot GET /wines". Here's code in app.js and src/routes/index.js:
// app.js
var express = require('express');
var app = express();
var path = require('path');
global.app = express();
require('./src/routes/index');
// also tried: require(path.join(__dirname, './src/routes/index'));
global.server = app.listen(3000, '0.0.0.0', function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
// ./src/routes/index.js
// tried console.error(app); and it printed all the stuff about app in the server log
app.get('/wines', function(req, res) {
res.send([{name:'w1'}, {name:'w2'}]);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
I'm sure I'm missing something. Any help is appreciated!
Problem
Honestly, I am not sure why what you are doing does not work.
The file can be found because otherwise, Node would throw an error, and the fact that you can access app from the routes file means app is accessible.
I have a suspicion that this may be due to garbage collection -- because you do not hold a reference to the module, it may be preemptively destroyed.
What's more, there is a construct in Express called a router that probably exists for this exact purpose.
Solution
While I'm not sure about the problem I am sure about the solution -- use a router, like this:
var express = require('express');
var router = express.Router();
router.get('/wines', function(req, res) {
res.send([{name:'w1'}, {name:'w2'}]);
});
router.get('/', function (req, res) {
res.send('Hello World!');
});
module.exports = router;
And then in your app.js file, do this:
var routes = require('./routes/index');
app.use('/', routes);
Another benefit of routers is that you do not have to pollute the global object anymore..
You need to use export in index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
and use it like this in app.js
var router = require('./src/routes/index');