Get 404 render view ejs with express js - javascript

I use express ejs on my backend and frontend. I have made a route to display the dashboard on the admin page. but I get 404 error to render view when I enter my url http: // localhost: 3000 /admin, here are some of my code:
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 admin = require('./routes/admin');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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('/admin', admin);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// app.use((req, res, next) => {
// res.status(404).render('error/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/404');
});
module.exports = app;
controller dashboard.js
exports.getDashboard = (req, res, next) => {
res.render('dashboard', {
pageTitle: 'Dashboard',
path: 'admin/page/dashboard'
});
};
my admin route admin.js
const path = require('path');
var express = require('express');
const adminController = require('../controllers/backend/dashboard');
var router = express.Router();
/* GET users listing. */
router.get('/admin', adminController.getDashboard);
module.exports = router;
thank you, please help me for this issue

in app.js you already have route /admin then again in admin.js, so it will be accessible with localhost:3000/admin/admin.
Change your admin.js to
const path = require('path');
var express = require('express');
const adminController = require('../controllers/backend/dashboard');
var router = express.Router();
/* GET users listing. */
router.get('/', adminController.getDashboard);
module.exports = router;

The problem is here:
const adminController = require('../controllers/backend/dashboard');
You are not exporting a default option from controller dashboard so you need to add curly braces like this:
const { adminController } = require('../controllers/backend/dashboard');
Try this and let me know! :)

Related

Routing keeps returning 404 instead of displaying other views besides index, users, and error in Express.JS

I am setting up a site on Express.JS with express-generator but ran into a hiccup with the routing. Currently I keep receiving the "error" view and a 404 message whenever sending a GET request to another route I set up ("/hook"). Currently the two routes that are working is "/" which goes to the "index" and "/users" which goes responds a message. I would like to see why I am getting this error as the others work.
Here is the app.js file:
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 usersRouter = require("./routes/users");
var hookRouter = require("./routes/hook");
var app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
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("/users", usersRouter);
app.use("/hook", hookRouter);
// 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;
Here is the index router
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Here is the hook router:
var express = require("express");
var router = express.Router();
/* GET hook page. */
router.get("/hook", function (req, res) {
res.send("Hook Page Works");
});
module.exports = router;
Please let me know there is any more info I can give. Thanks!
The hook router needs to be:
/* GET hook page. */
router.get("/", function (req, res) {
res.send("Hook Page Works");
});
This:
app.use("/hook", hookRouter);
has already used the /hook part of the path so within the router, you just want /.
Your original combination of:
app.use("/hook", hookRouter);
router.get("/hook", ...);
will respond to the URL /hook/hook.

404 Not Found nodejs to localhost

I am writing nodejs express to fetch the data to web page. an error appear 404 Not Found when open
http://127.0.0.1:3000/users
in the Dev tool on the browser show: users:1 GET http://127.0.0.1:3000/users 404 (Not Found)
below are the app.js and index.js and users.js files
I think I have an issue with the routes
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 expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');
var mysql = require('mssql');
// var connection = require('./lib/db');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
//I put false instead true
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: '123456cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))
app.use(flash());
app.use(expressValidator());
app.use('/', indexRouter);
app.use('/list', usersRouter);
// 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;
below are the routes files.
routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
routes/users.js
var express = require('express');
var router = express.Router();
var connection = require('../database.js');
/* GET home page. */
router.get('/', function(req, res, next) {
connection.query('SELECT * FROM users',function(err,rows) {
if(err){
req.flash('error', err);
res.render('list',{page_title:"Users - Node.js",data:''});
}else{
res.render('list',{page_title:"Users - Node.js",data:rows});
}
});
});
module.exports = router;
As I already mentioned in my comment, you don't have a /user route therefore you will get a 404 NotFound error.
Change this
app.use('/list', usersRouter);
To this
app.use('/user', usersRouter);

How to route the form action to a specific file by using express router

I'm using express.router and ejs template. I want the logic of one of my form with a POST method will be handled not in the app file (the main file of the application) but in some other file with the name 'user.js' using router.post. It returns 404 since it's trying to find the logic on the main file instead on the users.js file.
How can I route the post logic to be handled in the user.js file?
app.js file
const express = require('express');
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
var router = express.Router();
var usersRouter = require('./routes/users');
app.use('/users', usersRouter);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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')));
// 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;
users file (routes/users.js)
var express = require('express');
var app = require('../app')
const axios = require('axios');
var bodyParser = require('body-parser');
const {User} = require('../models/userModel')
const mongoose = require('mongoose');
const mongodb = require('mongodb');
const router = express.Router();
router.get('/', function(req, res, next) {
res.render("user");
});
router.post('/userSearch', (req, res) => {
res.send(req.body.myUser);
})
module.exports = router;
user file (views/user.ejs)
<h1>Welcome to users page</h1>
<form action="/userSearch" method="POST">
Search user:<input type ="search" name="myUser"></br>
<input type = "submit">
</form>
There are few unnecessary declarations on your files but the main reason your are not reaching the router path is because you are POSTing to a NOT declared route:
<form action="/userSearch" method="POST">
should be:
<form action="/users/userSearch" method="POST">
EXTRA
Few fixes for your files:
app.js
var router = express.Router(); //not needed here
users file (routes/users.js)
var app = require('../app') //not needed here

Express - get router.get to return json data attribute

I am new to javascript and would like to retrieve the json response from my express route get request. I can return the whole json but when i try to return a specific element i recieve an error (eg res.body.data). Here is my route file
route.js
var express = require('express');
var router = express.Router();
var request = require('request');
router.get('/', function(req, res, next) {
request({
uri: 'https://www.reddit.com/r/meme/new/.json'
}).pipe(res);
});
module.exports = router;
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 cors = require("cors");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require('./routes/testAPI');
var route = require('./routes/route');
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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/testAPI', testAPIRouter);
app.use('/route', route);
// 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;
You need to use body parser:
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));

Expressjs: throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

I have been having some problems with trying to get my code to work. I have tried a couple things but and it says my error is in line 28: "app.use('/','indexRouter')" but I have no clue why. My index.js file and app.js file are copies of each other.
My app.js file:
let express = require('express')
let path = require('path')
let favicon = require('serve-favicon')
let cookieParser = require('cookie-parser')
let bodyParser = require('body-parser')
let logger = require('morgan')
//Starts an express app
let app = express()
//Gives access to routes
//You will seperate each route base on different activites and group them that way
let indexRouter = require('./routes/index')
let userRouter = require('./routes/users')
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
routes.initialize(app);
app.use('/','indexRouter')
app.use('/users','userRouter')
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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');
});
//ALlows www to get access to it
module.exports = app
index.js file:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('index js stuff');
});
module.exports = router;
indexRouter and userRouter should not be a string.
app.use('/', indexRouter)
app.use('/users', userRouter)

Categories

Resources