My express server returns 404 error when i try to send request from html form. However get request works fine. I have separated files for server and routes. I can't make requests in app.js, because there are too many of them (for different pages). I want to make post-insert request to db, but i just can't get any information from my form.
Is there something i missing?
my html form (ejs precisely)
<form action="/add" method="POST">
<input type="text" name="title" placeholder="Event name" />
<input type="text" name="subcategory" placeholder="Category" />
<input type="text" name="date" placeholder="Date" />
<input type="text" name="place" placeholder="Place" />
<input type="text" name="organisator" placeholder="Organisator" />
<textarea name="description" placeholder="Description" onkeyup="adjust_textarea(this)"></textarea>
<input type="submit" value="Add" />
</form>
my App.js file (error on 404 handler)
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//db connection
var mysql = require("mysql");
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'mypassword',
database : 'mydb'
});
res.locals.connection.connect();
next();
});
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('/', require('./routes/index'));
app.use('/events', require('./routes/events'));
//handling errors
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//server init
var http = require('http');
var server = http.createServer(app);
server.listen(4000);
if(server.listening){
console.log('Server is listening on port 4000');
}
module.exports = app;
my ./routes/events.js file
const express = require('express');
const router = express.Router();
router.get('/', function (req, res, next) {
let query = '*select query*';
res.locals.connection.query(query, function (error, results, fields) {
if (error) throw error;
res.render('index', { title: 'Events', data: results });
});
});
router.post('/add', function (req, res) {
var obj = req.body.title;
console.log(obj);
res.redirect('/events');
});
What i see in browser
You have the 'add' endpoint listed in in your 'routes/events.js' file, which causes the structure of the final route to be '/events/add.' In your form, you are sending to the '/add' endpoint so to fix the issue, either change the action prop on the form to '/events/add' or move the '/add' endpoint into it's own route like this:
router.post('/add', function(req, res) {
var obj = req.body.title;
console.log(obj);
res.redirect('/events');
});
Related
I am using body-parser but it's not working and I don't know what the problem is.
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
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;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', redirection, function(req, res, next) {
res.redirect('index', {title: 'Home'});
});
router.get('/country', function(req, res, next) {
// CountryName
res.render('country',
{
title: 'Home',
mainJS: 'main.js',
//country: req.body.countries
});
console.log(req.body)
});
function redirection(req, res){
if (req.url == '/'){
res.redirect('/country');
}
}
module.exports = router;
In this code it throws {}
What is the problem?
Your server only receives a request body in POST (or PUT or PATCH) operations, not in GET operations. You don't have router.post() in your sample code, so it seems you are not handling POSTs. Therefore, no req.body.
You can find your https://example.com/?query=parameters&query2=parameters at req.params.query and req.params.query2.
You can't use the location bar of a browser to do a POST: they from a form posts or xhr / fetch operations.
I'm currently learning and a newbie to Node.js. I'm trying to build a simple REST API and currently getting an error 404 when try post to a particular route in postman to test if data has successfully been sent to Mongo db. I'm sure what i'm missing. I have double checked all my routes and they seem fine. It works when i make a get request and falls through when i make a post request.
This is my app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var Developer = require('./models/developers');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// Connect to DB
mongoose.connect('mongodb://127.0.0.1:27017');
// API Routes
var router = express.Router();
// Routes will be prefixed with /api
app.use('/api', router);
// 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;
// Test Route
router.get('/', function (req, res) {
res.json({message: 'Welcome to my simple API!'});
});
router.route('/developers')
.post(function (req, res) {
var developer = new Developer(); // New instance of sa developer
developer.firstName = req.body.firstName;
developer.lastName = req.body.lastName;
developer.jobTitle = req.body.jobTitle;
developer.save(function (err) {
if (err) {
res.send(err);
} else {
res.json('Developer was successfully fetched');
}
});
})
.get(function (req, res) {
Developer.find(function (err, developers) {
if (err) {
res.send(err);
} else
res.json(developers);
});
});
router.route('/developer/:developer_id')
.get(function (req, res) {
Developer.findById(res.params.developer_id, function (err, developer) {
if (err) {
res.send(err);
}
res.json(developer);
});
});
router.route('/developer/firstName/:firstName')
.get(function (req, res) {
Developer.find({firstName:res.params.firstName}, function (err, developer) {
if (err) {
res.send(err);
}
res.json(developer);
});
});
My model is developer.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DevelopersSchema = new Schema({
firstName: String,
lastName: String,
jobTitle: String
});
module.exports = mongoose.model('Developers', DevelopersSchema);
To connect the database, instead of
mongoose.connect('mongodb://127.0.0.1:27017');
Use,
mongoose.connect('mongodb://127.0.0.1:27017/yourDatabaseName');
Check the doc.
Mongoose database connection require a database name in connect() method.
Your final app.js should be like,
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var Developer = require('./models/developers');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// Connect to DB
mongoose.connect('mongodb://127.0.0.1:27017/my_unique_data_base_name');
// API Routes
var router = express.Router();
// Routes will be prefixed with /api
app.use('/api', router);
// 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;
// Test Route
router.get('/', function (req, res) {
res.json({message: 'Welcome to my simple API!'});
});
router.route('/developers')
.post(function (req, res) {
var developer = new Developer(); // New instance of sa developer
developer.firstName = req.body.firstName;
developer.lastName = req.body.lastName;
developer.jobTitle = req.body.jobTitle;
developer.save(function (err) {
if (err) {
res.send(err);
} else {
res.json('Developer was successfully fetched');
}
});
})
.get(function (req, res) {
Developer.find(function (err, developers) {
if (err) {
res.send(err);
} else
res.json(developers);
});
});
router.route('/developer/:developer_id')
.get(function (req, res) {
Developer.findById(res.params.developer_id, function (err, developer) {
if (err) {
res.send(err);
}
res.json(developer);
});
});
router.route('/developer/firstName/:firstName')
.get(function (req, res) {
Developer.find({firstName:res.params.firstName}, function (err, developer) {
if (err) {
res.send(err);
}
res.json(developer);
});
});
if I'm correct, the line of app.use('/api', router); does nothing.
When coming a request for /api endpoint, a response should be sent at the end of operations. The code pass the request to router. And router does nothing.
Then if createError(404) method calls res.send() or res.end() methods
you should move the use() method to the bottom of your code page:
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
Because at every single time it works before the other routes.
IMHO, using a standard coding style make more readable the program-flow.
Good luck..
i have installed body parser through npm, required it, set it with express buti am still getting req.body undefined. If someone knows whats wrong please let me know i feel like its something stupid im missing.
This is my app.js file
const express = require('express')
const index = require('./routes/index');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
//Create the express server
const app = express();
// Use index routes file
app.use('', index);
// Use the /public folder for our assets
app.use('/public', express.static('public'));
// Use body-parser and cookie-parser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cookieParser);
// Set ejs as our templating engine
app.set('view engine', 'ejs');
// Catch 404 and forward to error handler
app.use(function(req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// Error handler
app.use((err, req, res, next) => {
res.locals.message = err.message;
res.status(res.statusCode || 500);
res.render('error', {error: err.message});
console.log(err.message);
});
app.listen(process.env.PORT || 3000, () => {
console.log('Application running on localhost:3000');
});
This is my route index.js file that's making the post
const express = require('express');
const router = express.Router();
const fs = require('fs');
const movie_controller = require('../controllers/movieController');
const bodyParser = require('body-parser');
const request = require('request');
router.get('/about', (req, res, error) => {
res.render('about');
});
router.get('/', movie_controller.get_index);
router.get('/currently_playing', movie_controller.get_currently_playing);
router.get('/top_rated', movie_controller.get_top_rated);
router.get('/upcoming', movie_controller.get_upcoming);
router.get('/movie_view/:id', movie_controller.get_movie);
// Post request for a search query
router.post('/search', (req, res, next) => {
console.log('Query', req.body);
// Make request for query
request('https://api.themoviedb.org/3/search/movie?api_key=&language=en-
US&query=' + req.body + '&page=1&include_adult=false', (error, response,
body) => {
//handle errors
if(error){res.render('error', {error: error.message})}
//handle body
if(response.statusCode === 200){
//place body data in a variable for later reference
let movieData = JSON.parse(body);
let movies = [];
movieData.results.forEach(movie => {
movies.push(movie);
});
// Make request for genres
request('https://api.themoviedb.org/3/genre/movie/list?
api_key=&language=en-US', (error, response, body) => {
//handle errors
if(error){res.render('error', {error: error.message})}
//handle body
if(response.statusCode === 200){
//place body in a variable for later reference
let genreData = JSON.parse(body);
let genres = [];
genreData.genres.forEach(genre => {
genres.push(genre);
});
res.render('results', {movie: movies, genres: genres });
}
})
}
})
});
module.exports = router;
This is where the form is on a header.ejs partial
<form class="form-inline my-2 my-lg-0" action="/search" method="post">
<input class="form-control mr-sm-2" type="search" placeholder="Search" name="searchQuery" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>enter code here
You should to use the bodyParser() before app.use('', index) of your router, to avoid any problem just place app.use('', index) it in the last.
// Use body-parser and cookie-parser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cookieParser);
// Use index routes file
app.use('', index);
Express middleware runs in the order you register them (routes included). You have registered the bodyParser and cookieParser middlewares after attaching your routes. Therefore, you will not have the parsed body or cookies by the time your route is encountered.
To fix this, make sure that any middlewares you want to run before your actual route are registered before:
const express = require('express')
const index = require('./routes/index');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
//Create the express server
const app = express();
// Use the /public folder for our assets
app.use('/public', express.static('public'));
// Use body-parser and cookie-parser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cookieParser);
// Use index routes file
app.use('', index);
...
I try to send a form with data in my nodejs app but I get "undefined" I am not sure does it matter but in console first I see "undefined", then POST. I have tried some "fixes" from the Internet like adding "type:'application/*+json', inflate: false" to app.use(bodyParser.json...) but nothing worked for me...
Undefined
POST /users/register 200 32.777 ms - 2346
this is my routes/users.js file:
var express = require('express');
var router = express.Router();
router.get('/register', function(req, res, next) {
res.render('register', {
'title': 'Register'
});
});
router.post('/register', function(req, res, next) {
console.log(req.body.name);
});
module.exports = router;
heres my jade file
form(method='post', action='/users/register', role='form')
.form-group
label Name
input.form-control(type='text', name='name', placeholder='Enter Name')
input.btn.btn-default(name='submit', type='submit', value='Register')
and app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json({ type: 'application/*+json' }));
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
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
});
});
}
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Routing works fine what show setting up a title to "Register", but I have problems with sending post :/
You're configuring body-parser to only accept JSON request bodies, but your form is submitted in URL-encoded format (application/x-www-form-urlencoded).
For that, you need to add the correct parser:
app.use(bodyParser.urlencoded({ extended : true }));
More information, also on the meaning of extended : true, here.
No matter what link I declare in the action of my form, it always returns an 404 error. if I change the method to get, it doesn't.
I want to use post because i'm trying to get the data from my input fields and post it in my mongedb database:
HTML:
<form class="container-fluid searchContainer" action="/active" method="post">
<div class="col-xs-6">
<div class="form-group">
<label for="businessUnit">Business unit</label>
<input type="text" ng-model="businessUnit" id="businessUnit" name="businessUnit" class="form-control"/>
</div>
<div class="form-group">
<label for="tenderId">Tender ID</label>
<input type="text" name="tenderID" ng-model="tenderId" id="tenderId" class="form-control"/>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="tenderDate">Tender Bidding Date</label>
<input type="date" ng-model="tenderDate" name="tenderDate" id="tenderDate" class="form-control"/>
</div>
<div class="form-group">
<label for="therapyArea">Therapy area</label>
<input type="text" ng-model="therapyArea" name="therapyArea" id="therapyArea" class="form-control"/>
</div>
</div>
<div class="col-md-12 text-right">
<input type="submit" id="btnCreate" value="Create" class="btn btn-primary" >
</div>
</form>
JAVASCRIPT:
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 active = require('./routes/active');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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);
app.use('/active', active);
// 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;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tenders');
var db = mongoose.connection;
db.on('error', function(err) {
console.log('connection error', err);
});
db.once('open', function() {
console.log('connected.');
});
var Schema = new mongoose.Schema({
TenderID: String,
TenderDate: String,
BusinessUnit: String,
TherapyUnit: String
});
var Tender = mongoose.model('Tender', Schema);
app.post('/active', function(req, res) {
new Tender({
TenderID: req.body.tenderID,
TenderDate: req.body.tenderDate,
BusinessUnit: req.body.businessunit,
TherapyUnit: req.body.therapyUnit
}).save(function(err, doc) {
if (err) res.json(err);
else res.send('Succesfully insterted')
})
});
Because you define your 404 route handler before you define app.post('/active'), express evaluates the 404 rule first and returns it. Your POST /active route never gets evaluated. To fix this you need to give Express your POST /active route before your 404 route (which should always be your last route).
Unless you have an equivalent POST /active route defined in the file ./routes/active, the line
app.use('/active', active);
won't fix this problem even though it is evaluated before your 404 route. You can read more about app.use() vs app.get|post|etc() in the express docs.
Express evaluates rules in the order they are passed to it via use() or get|post|delete|etc()
You have defined get route in your server. Try to change the
app.get('/active',function(req,res){
into
app.post('/active',function(req,res){
In this way, you will respond to a post request from the browser.