I am fairly new to programming, and am struggling with trying to get the recipe.ejs file to show. I cannot seem to create a route from recipe.js properly to get the recipe.ejs file and render it. Any help would be greatly appreciated.
/routes/recipe.js
var express = require('express');
var router = express.Router();
/*GET recipe page*/
router.get('/', function(req, res, next) {
res.render('recipe');
});
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 indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var recipeRouter = require('./routes/recipe');
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('/recipe', recipeRouter);
// 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;
Try with this proved snippet:
package.json
server.js
views/hello.ejs
server.js
var express = require('express');
var app = express();
app.get("/", function(req, res) {
res.render("hello.ejs");
});
app.listen(2708, function() {
console.log("server is listening!!!");
});
hello.ejs
<h1>Hello EJS World </h1>
package.json
{
"name": "first-express-app",
"description": "an example of using Express",
"private": true,
"version": "0.0.1",
"dependencies": {
"ejs": "^3.1.3",
"express": "4.17.1"
},
"scripts": {
"start": "node server"
},
"main": "quote"
}
If it works, you could use to compare it with your complex implementation to find the error.
Related
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);
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 }));
I've been trying to fix this for 2 hours now and I'm getting a little frustrated. Basicly, I want to validate a form input, but I always get this error.
TypeError: req.checkBody is not a function
at C:\Users\bobbo\Desktop\Develops\Project_folder\routes\index.js:19:7
at Layer.handle [as handle_request] (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:47:12)
Pretty much the only info I could find is telling me to write the app.use(expressValidator());
after app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));, but it doesn't matter what I do, I still get the same error. Here is the code I use.
//index.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var expressValidator = require('express-validator');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/signup', function(req, res, next) {
res.render('signup', { title: 'Express' });
});
router.post('/signup', function(req, res){
var name = req.body.name;
console.log(name); //works
req.checkBody("name", "Invalid name").notEmpty();
var errors = req.validationErrors();
if(errors){
console.log('errors');
} else{
console.log('no errors');
}
});
module.exports = router;
app.js
//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 bodyParser = require('body-parser');
var expressValidator = require('express-validator');
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', 'pug');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
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);
// 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;
package.json
//package.json
{
"name": "pizzaonline",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "^1.18.3",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-session": "^1.15.6",
"express-validator": "^5.2.0",
"http-errors": "~1.6.2",
"morgan": "~1.9.0",
"pug": "2.0.0-beta11"
}
}
If I comment out req.checkBody("name", "Invalid name").notEmpty();, the next express-validation code to be executed is var errors = req.validationErrors();, giving me an identical error telling me req.validationErrors() is not a function. I'm new to this but this tells me that express-validator is not properly installed, am I wrong? Any help is much appreciated. Thanks in advance.
In Your nested route files (index.js and users.js) You're creating new app instance and attaching that validator to it that in fact is not correct.
Cause by creating new app instance You create new app context that is different from app in app.js.
So here's the fix:
1) attach express validator above this lines in app.js file:
app.use(expressValidator());
app.use('/', indexRouter);
app.use('/users', usersRouter);
2) remove app object generation from nested route files and make it look like:
//index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/signup', function(req, res, next) {
res.render('signup', { title: 'Express' });
});
router.post('/signup', function(req, res){
var name = req.body.name;
req.checkBody("name", "Invalid name").notEmpty();
var errors = req.validationErrors();
if(errors){
console.log('errors');
} else{
console.log('no errors');
}
});
module.exports = router;
npm i --save express-validator#4
reqiure app.js
app.use(expressValidator());
and try again
npm start
Currently my code is this:
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var data = {
"1": 127,
"2": 236,
"3": 348
}
router.get('/', function(req, res, next) {
res.send(data);
});
router.get('/:id', function(req, res, next) {
var key = req.params.id;
res.send({ [key]: data[key] });
});
router.post('/:id', function(req, res, next) {
var id = req.params.id;
console.log(id);
})
My goal is to be able to POST a value from Postman to API/values/:id, save that value under the id key and then save that "key": value pair in the data variable. Unfortunately, when I try to POST anything and then access it with req.body, I get {} or undefined.
app.js
var routes = require('./routes/');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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(expressSession({
secret: 'secretText',
saveUninitialized: true,
resave: true
}))
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes.home);
app.use('/values', routes.values);
// 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');
});
module.exports = app;
To do so you need to have body-parser plugin of expressjs.
Install it using npm install --save body-parser and then use it like below
var bodyParser = require('body-parser');
express()
.use(bodyParser.urlencoded({
extended: true
}))
.use(bodyParser.json())
When I run the localhost:3000/users/yu , I get a 404 not found. Why is the post() coming up as undefined? when I run a POST from my iOS app I get a "undefined token" error. I'm running node v5.7.0 and express v4.13.4 Project was generated using express-generator to create Webstorm project.
var express = require('express');
var router = express.Router();
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res) {
res.send("yoma");
});
router.post('/yu', function(req, res) {
var test = req.body;
//parse test
});
My app.js looks like this:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
when you navigate your browser to localhost:3000/users/yu it makes GET http query, but in your router you have only POST handler for '/yu'
router.post('/yu', function(req, res) {
console.log(req.body);
});
Add GET handler for '/yu' like this for example
router.get('/yu', function(req, res) {
console.log(req.body);
});
After that you should not get a 404 error when navigate to localhost:3000/users/yu