Cannot POST using express and body-parser - node.js

Please can you help me out, for some reason I am not able to post and am getting a "cannot POST /api/create" and when inspecting the page a 404 error is shown.
Here is my index.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mainRouter = require('./mainRouter.js');
var todoRoutes = require('./todoRoutes.js');
//tell express to use bodyParser for JSON and URL encoded form bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//mouting our routers
app.use('/', mainRouter);
app.use('/todo',todoRoutes);
app.listen(3000);
console.log("Express server running on port 3000");
And the corresponding todoRoutes.js file is where I require the post method:
var express = require('express');
var todoRoutes = express.Router();
var todoList = []; //to do list array
todoRoutes.get('/', function(req, res) {
res.sendFile(__dirname + '/views/todo/index.html');
});
todoRoutes.get('/create', function(req, res) {
res.sendFile(__dirname + '/views/todo/create.html');
});
todoRoutes.get('/api/list', function(req, res) {
res.json(todoList); //respond with JSON
});
todoRoutes.get('/api/get/:id',function(req, res){
res.json(todoList[req.params.id]);
});
todoRoutes.post('/api/create', function(req, res){
console.log("Creating the following todo:", req.body.todo);
todoList.push(req.body.todo);
res.send({redirect: '/api/list'});
});
and here is the corresponding html file:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Todo List: Create</title>
<meta charset="utf-8" />
</head>
<body>
<form action = "/api/create" method="post">
<div>
<label for="todo">Enter your new Todo:</label>
<input type="text" id="todo" name="todo">
</div>
<div class="button">
<button type="submit">Add</button>
</div>
</form>
</body>
</html>
If I put a console.log("") in the POST function of the todoRoutes.js file it will not be displayed, indicating that the function does not even get executed.
Any help will be very much appreciated.

You need to POST to /todo/api/create, based on your current route handling:
<form action = "/todo/api/create" method="post">

Related

how to pass variable from one ejs to another ejs in node js

I have two ejs in my views folder
I have created very simple ejs to see if I can send the variable from one ejs to another ejs.
a.ejs in veiws file
<form name="input" action="\home" method="post">
<input type='checkbox' checked>Cheese
<input type="submit" value="Submit" href="validation.ejs">
</form>
b.ejs has
<h1><% post my variable here%></h1>
in my node js this is what i did
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { title: 'EJS Demo' });
});
app.post('/', (req, res) => {
const a = req.body.a;
res.get('index2',a);
});
app.listen(3000, () => {
console.log('Listening....');
});
i think the post has to do something in here...
I think you need to submit a value from form1 in page1 and pass that variable to page2
if thats the case you can do like this
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
// send the page1 to the user
app.get('/', (req, res) => {
res.render('page1', { title: 'EJS Demo' });
});
//capture the submit from the user and then send another page
//to the user
app.post('/submitForm', (req, res) => {
const a = req.body.valueFromA;
res.render('page2',a);
});
app.listen(3000, () => {
console.log('Listening....');
});
<form name="input" action="\home" method="post">
<input type='checkbox' checked>Cheese
<input type="submit" value="Submit" href="validation.ejs">
</form>
<!-- page1 form1 -->
<html>
<head>
<title> <& title &> </title>
</head>
<form action='/submitForm' method='post'>
<input type='text' value='' name='valueFromA' />
<input type='submit' />
</form>
</html>
<!-- page2 ejs -->
<html>
<body>
<p> <% value %> </p>
</body>
</html>
b.ejs has
<h1><% post my variable here%></h1>
in my node js this is what i did const

Cannot post to a server in express

I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.
app.js:
var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();
app.engine('html', consolidate.nunjucks);
app.set('view engine', 'html');
app.set('views', './views');
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(3055);
module.exports = app;
routes/index.js:
const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();
router.get('/', function(req, res, next){
res.render('index.html');
});
router.post('/addsubject', function(req, res, next){
Patient.create(req.body).then(function(patient){
res.redirect('/profile');
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
} else {
return next(err);
}
}).catch(function(error){
res.send(500, error);
});
});
router.get('/profile', function(req, res, next){
res.render('./profile.html');
});
router.get('/addsubject', function(req, res, next){
// .... do something here ..
});
module.exports = router;
I have the <form action="/addsubject" method="post"> in my index.html file.
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>dabl Demographic</title>
<body>
<h2>Add Subject</h2>
<form action="/addsubject" method="post">
<label for="fname">First Name: </label>
<input type="text" name="fname" id="fname">
<br>
<label for="sname">Second Name: </label>
<input type="text" name="sname" id="sname">
<br>
<label for="dob">dob: </label>
<input type="text" name="dob" id="dob">
<br>
<label for="laterality">Laterality: </label>
<input type="text" name="laterality" id="laterality">
<br>
<button>Submit</button>
</form>
</body>
</html>
You pass wrong function (error handling function) to the POST route.
Just remove first "err" param from the function like this:
router.post('/addsubject', function(req, res, next){
Use body-parser middleware before app.router
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...
Problem solved:
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
next(err); //next(err); called inide this block no more 404 error
}
User input is now succesfully passed through the body-parser.

Express nodejs req.body returns undefined

I'm trying a simple form submission code, and I'm using post method.
My server.js code
//N-4E;V-56;I-49
//var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var idx = require('./index.js');
var ra = require('./ra.js');
var app = express();
app.engine('html',require('ejs').renderFile);
app.set('view engine', 'html');
app.set('port',process.env.PORT || 5649);
app.use(bodyParser.urlencoded({extended: true}));
app.use('/',idx);
app.use('/reg_path',ra);
app.listen(app.get('port'),function(){
console.log('Express started press asdfadsfasdfasdf');
});
my index.js
var express = require('express');
var fs = require('fs');
var router = express.Router();
router.get('/',function(req,res,next){
//res.sendHeader(.)
res.render('index.ejs',{});
//res.render('title.ejs',{});
});
module.exports = router;
my index.ejs
<!DOCTYPE html>
<html>
<head>
</head>
</body>
<div id="reg_path">
<p>Enter the Regressions Folder Path</p>
<form action="/reg_path" method="post" enctype="multipart/form-data">
<fieldset>
<label for="path">Path:</label>
<input type="text" id="path" name="path" placeholder="Enter the Absolute path"/>
<input type="submit" value="Enter"/>
</fieldset>
</form>
</div>
</body>
</html>
my ra.js is
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express.Router();
var path;
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post("/",function(req,res){
console.log(req.body.path);
path = req.body.path;
fs.access('path',fs.constants.F_OK, (err) => {
if (err) throw err;
res.redirect('./index');
//if (err) {
// res.writeHead(404,{'Content-Type':'text/plain'});
// return res.end('The specified path "' + path + '" does not exists');
//}
});
//fs.access('path',fs.constants.R_OK, (err) => {
// //if (err) {
// // res.writeHead(404,{'Content-Type':'text/plain'});
// // return res.end('The specified path "' + path + '" has no READ permissions');
// //}
//});
});
module.exports = app;
Now, from the index page, when I type a path in the form, and press the submit, in the console.log the 'req.body' is returned as 'undefined'.
most of the code in ra.js is commented or not updated because the 'req.body' value is unavailable in the first place. I need to correct it first.
I've searched through internet to try and figure out the mistake that is in my code, but to my vain I'm unable to uncover it. Any help is much appreciated
node version:v6.11.0
body-parser :1.17.2
express :4.15.3
ejs :2.5.6
Your form uses enctype="multipart/form-data" which is an encoding type that body-parser doesn't support.
If you need to use this type (for instance, if you're going to be uploading files from your form), take a look at multer.
Otherwise, leave out the enctype attribute so the form will default to application/x-www-form-urlencoded.

Why can't I get post parameters?

This is my HTML
<!DOCTYPE HTML>
<html>
<head>
<title>Page d'inscription/connexion</title>
</head>
<body>
<form method="POST" action="/join" enctype="multipart/form-data">
Pseudo:<br>
<input type="text" name="pseudo"><br>
<input type="submit" value="S'inscrire">
</form>
</body>
</html>
and this is my nodeJs
var express = require("express");
//use the application off of express.
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
//define the route for "/"
app.get("/", function (request, response){
console.log("aaa")
response.sendFile(__dirname+"/index.html");
});
app.post("/join", function (request, response){
var pseudo = request.body.pseudo;
console.log(pseudo)
if (pseudo != "") {
response.send("Your pseudo address is " + pseudo + " ");
} else {
response.send("Please provide us pseudo");
}
});
//start the server
app.listen(8080);
console.log("Something awesome to happen at http://localhost:8080");
Why, when i put "Monsieur Dupont" as pseudo and then I submit the button, pseudo is undefined instead of being Monsieur Dupont ?
Please help me i am blocked
simply remove enctype="multipart/form-data" it will work fine.

Getting a HTTP 404 error when doing app.post in Node.js

I am newbie to Node.js trying to learn through tutorials found online using Netbeans.
When I do: http://localhost:9080/ I see the Date and the color as expected. But when I try to do http://localhost:9080/add, to see the app.post part, I get HTTP 404 error.
Could anyone let me know what am i doing wrong.
Thanks in advance,
ind.ejs
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h1> my app </h1>
<%= new Date() %>
Color is:
<%= test %>
</body>
</html>
index.js:
'use strict';
module.exports = require('./lib/express');
var http = require('http');
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var app = express();
var tropo_webapi = require('tropo-webapi');
var bodyParser = require('body-parser');
var test;
var app = express();
//app.use(bodyParser());
app.set('view engine','ejs');
app.set('views', path.join(__dirname,'views'));
app.get('/',function(req,res){
var test = 'red';
console.log('test in get is :' + test);
res.render('ind.ejs',{test:test});
});
app.post('/add',function(req,res){
test = 'blue';
console.log('test in post is :' + test);
res.render('ind.ejs',{test:test});
});
app.listen(9080, function(){
console.log('Ready on port 9080');
});
app.get is for the 'GET' http verb, which is used by default. app.post is triggered for the 'POST' http verb, which can be done using forms:
<form action="/add" method="post"><button type="submit">go</button></form>

Resources