Main index route is working, all others are not - express

Can anyone help me figure out why my express routes arent working please. I have been stuck for days trying to figure this out but I keep getting 404 errors when I got to any of the routes in customer.js
<--------------------main server-------------->
var express = require("express");
var path = require('path');
var app = express();
var indexRouter = require('./routes/index');
var ordersRouter = require('./routes/orders');
var customersRouter = require('./routes/customers');
var productsRouter = require('./routes/products');
app.use('/', indexRouter);
app.use('/customers', customersRouter);
app.use('/orders', ordersRouter);
app.use('/products', productsRouter);
app.listen(80);
module.exports = app;
one of my route files below the only route file works is the index router.
var express = require('express');
var router = express.Router();
router.get('/customers', function(req, res, next) {
console.log(req.status())
res.send('<p>some html</p>');
});
router.post('/customers/update/shipping', function(req, res) {
res.send('<p>someg html</p>');
});
router.post('/customers/update/billing', function(req, res) {
res.send('<p>somew html</p>');
});
router.post('/customers/update/cart', function(req, res) {
res.send('<p>some dhtml</p>');
});
module.exports = router;
<------------------------------------------------------>

In your customers files your routes will already be relative to /customers. remove the leading /customers from all your routes. For e.g:
router.get('/customers', function(req, res, next) {
console.log(req.status())
res.send('<p>some html</p>');
});
Should just be
router.get('/', function(req, res, next) {
console.log(req.status())
res.send('<p>some html</p>');
});
same principle applies for the other files.

Related

express routes not working - returning 404 error

I'm trying to set up a simple express project, and backend will be purely for api and frontend will be vue. I tried adding an api router, and not only does it not work, but even the root page doesn't work. I've not coded in express for a very long time, and wondering if some one could guide me on what's the problem? The error message is 404 NotFoundError: Not Found.
I'm navigating to localhost:3000, and I can see the call on the terminal, so port should be correct too?
/src/api/urls.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('Just a test');
});
module.exports = router;
I didn't change the folder structure/naming for the original routes/index.js.
/src/routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('Just a test');
});
module.exports = router;
And for the main file
/src/app.js
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 apiRouter = require('./api/urls');
var app = express();
app.use(require('connect-history-api-fallback')());
// 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(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/api', apiRouter);
// 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;
All good except endpoint url that should be with middleware function only. Modifying these should work,
/src/api/urls.js
var express = require('express');
var router = express.Router();
router.get('/api/test', function(req, res) {
res.send('Just a test');
});
module.exports = router;
/src/routes/index.js
var express = require('express');
var router = express.Router();
router.get('/api/test2', function(req, res) {
res.send('Just a test');
});
module.exports = router;
In app.js you should register your routes as,
// Routes
app.use([
require('./src/api/urls'),
require('./src/routes/index'),
]);
Access by url ( http://<yourhost>/api/test1 )

expressjs req.body is empty

Banging my head on this. in Express app, my get request works fine. However attempting to POST results passes an empty req.body.
here is my file tree:
index.js:
const express = require('express');
const apiRoute = require('./routes/api/index.js');
const bodyParser = require('body-parser');
// const morgan = require('morgan');
const app = express();
app.use(function(req, res, next) {
if (req.headers['content-type'] === 'application/json;') {
req.headers['content-type'] = 'application/json';
}
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api', apiRoute);
app.listen(3000);
routes/api/index.js
const express = require('express');
const router = express.Router();
const entityRoute = require('./entity');
router.use('/entity', entityRoute);
module.exports = router;
routes/api/entity.js:
const express = require('express');
const router = express.Router();
const db = require('../../database');
router.get('/', function(req, res) {
db.select().from('entity').then(function(data) {
res.send(data);
});
});
router.post('/', function(req, res) {
console.log(req.body);
res.send(req.body);
});
module.exports = router;
Adding my Postman request in response to comment:
I have been over this numerous times, checked body-parser docs and other SO answers and can't figure this out.
following the comments, submitting json body works. screenshot below:
Not sure why this doesnt work the other way...

Mean Stack Root Routing is not working

Can someone help me why default route is not working in my Mean App, But the next routing works
Here when I open http://localhost:3000 I am not able to see any output, But I have defined route in route.js which is working
var express = require('express');
var cors = require('cors');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
const port = 3000;
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
When I open the page with http://localhost:3000/main I am able to see the Output and also log written in the console
const express = require('express');
const router = express.Router();
router.get('/main', function (req, res, next) {
res.send('This is the Admin Landing Page');
});
router.get('/install', function (req, res, next) {
res.send('This is the Install Landing Page');
console.log('Opened the Install path');
});
module.exports = router;
It looks like you the code you pasted is the full version, and it's not runnable because:
You did not declare app variable.
You did not start the http server.
It's really hard to tell the root cause what's wrong of your code. Following codes works for me:
const express = require('express');
const port = 3000;
let app = express();
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
let server = require('http').createServer(app);
server.listen(port, function() {
console.log('Server started');
});

Express route function not showing text

app.js :
var index = require('./routes/index2');
var users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
index2.js :
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
when I go to localhost:3000/ I don't see the text in send function
I guess your browser is you waiting for a response?
If you change index2.js to be a function and return the router, you'll be adding it as a middleware with app.use('url', middleware). I hope this helps
app.js
var index = require('./routes/index2');
var users = require('./routes/users');
app.use('/', index()); //Invoke the object to get the router back
app.use('/users', users);
index2.js
var express = require('express');
var router = express.Router();
module.exports = function() {
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
return router;
};
Returning the router from index2 to be used as a middleware

Express.js, req.params not being called

So i have been racking my brain for quite awhile now trying to figure this out and I'm still having issues.
So i define a route like this:
var home = require('./routes/home');
var app = express();
app.use('/home/:client', home);
And my home.js code looks like this:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('homeview', { title: 'Welcome',
user: username});
});
router.get('/:client', function(req, res, next) {
var theClient = req.params.client;
console.log(theClient)
});
module.exports = router;
And then when i try to go to this URL:
http://www.localhost:3000/home/client
Nothing happens. For some reason it never gets to the second router.get and never logs anything. Anyone notice whats wrong?
Working solution # https://github.com/rmjoia/expressRoutes
app.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
homeRouter = require('./home');
app.use('/home', homeRouter);
app.route('/')
.all(function (request, response, next) {
// Do some plumbing stuff
next();
})
.get(function (request, response, next) {
response.send('OK GET - Hello Stack Overflow');
next();
});
app.listen(port, function (error) {
if (error) {
console.error(error.message);
}
else {
console.info('Server up and running. Listening on port ' + port);
}
})
home.js
var express = require('express');
var homeRouter = express.Router();
var router = (function (router) {
// define the home page route
router.get('/', function (req, res) {
res.send('home route - homepage');
});
// define the about route
router.get('/:client', function (req, res) {
res.send(req.params.client);
});
return homeRouter;
})(homeRouter);
module.exports = router;