Sparksido Sparksido - 6 months ago 17
Node.js Question

Why is the directory throwing 404 when rendering ejs

I am trying to make a page which just receives a get request from my index.js file and just displays "hello user". I have created a 'users.ejs' file in my express app which just renders a string from a 'users.js' file. There is a form in my index.ejs file which redirects to my users directory. The index file works well when I type the '/' directory in the url box but for some reason, the file throws a 404 not found error in the browser when I hit the submit on the form in the first page instead of showing the 'users.ejs' page, can anyone tell me why it does this?

index.ejs



<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p><br>

<form action='/users' method='get'>
Enter Name: <input type='text' name='thetext'></input><br><br>
<input type='submit' id='checkresponse'>enter</button>
</form>

<script type = 'text/javascript' src = '/dist/jquery.js'></script>
<script type = 'text/javascript' src = '/js/response.js'></script>
</body>
</html>





index.js



var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Expr-Ass' });
});

module.exports = router;





users.js



var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/users', function(req, res, next) {
res.render('users', {star:'Sparksiano'});
});

module.exports = router;





users.ejs



<!DOCTYPE html>
<html>
<head>
<title><%= star %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>Welcome user!</h1>

</body>
</html>




Answer

Based off of comments below you may want to try something like this:

users.js

var express = require('express');
var router = express.Router();

/* Notice the path change */
router.get('/', function(req, res, next) {
  res.render('users', {star:'Sparksiano'});
});

module.exports = router;

It sounds like you may be mounting your path to include a /users and then having a route that has a path of /users. Would be easier to troubleshoot if you posted the rest of the server side code.

Comments