Why I still get the "Cannot POST" message? - node.js

I have a very simple html form, and express server, but I can't make the routing work. I always get "Cannot Post" message. What did I miss?
var express = require('express');
var bodyparser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
app.use(express.bodyParser());
app.get("/", function(req, res){
res.sendFile(path.join(__dirname+"/index.html"));
});
app.post("/sendform", function(req, res){
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function(){
console.log("Server is running at port: 3000");
});
<form method="post" action="http://localhost:3000/sendform">
<input type="text" name="username" />
<input type="submit" value="küldés" />
</form>

With express 4.15.3, you have to use the body parser a bit differently.
I changed your code to this and I was able to post to it:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
//app.use(express.bodyParser());
app.use(bodyParser.json({
limit: "10mb"
}));
app.use(bodyParser.urlencoded({
limit: "10mb",
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post("/sendform", function (req, res) {
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function () {
console.log("Server is running at port: 3000");
});

Related

How can I receive post data in a node js server with express?

I tried two middlewares but still getting this output in the terminal:
{}
my node js server code:
express = require('express');
bodyParser = require('body-parser');
const app = express();
//the middlewares i tried
app.use(express.urlencoded({extended: false}));
app.use(bodyParser());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/client.html');
});
app.post('/test', (req, res) => {
res.send('this is a test path');
console.log(req.body);
});
app.listen(3000, () => {
console.log('server listening...');
});
my form (client.html file):
<form method="POST" action="/test">
<input type="text">
<input type="submit">
</form>
I also tried send the post data with postman. I know that the action in the html form is working because I can see the "this is a test path" output in the browser
try this
express = require('express');
bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/client.html');
});
app.post('/test', (req, res) => {
res.send('this is a test path');
console.log(req.body);
});
app.listen(3000, () => {
console.log('server listening...');
});
also in html form , add name property in input tag
<form method="POST" action="/test">
<input type="text" name="email">
<input type="submit">
</form>
in fact it works just like
app.use(express.urlencoded());
the wrong thing was the nameless input in the html form
you should write code like this
var app=express();
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
app.post('/test', (req, res) => {
console.log(req.body.email);
res.send('this is a test path'+req.body.email);
});

NodeSSPI 2 Minute Timeout on Post

When I send a request to my server I have no problem, but when I POST I run into a server timeout. (2 minutes by default, but if I add server.setTimeout(15000) I get a 15 second delay.) Once the server times out the process completes as expected. Interestingly, if I add a console.log(res) before the res.finished || next() the delay goes away.
post.html:
<form action="http://localhost:3000" method="post">
<input type="text" name="user[name]">
<input type="text" name="user[email]">
<input type="submit" value="Submit">
</form>
test.js:
'use strict'
var express = require('express')
var app = express()
var server = require('http').createServer(app)
//server.setTimeout(15000);
const bodyParser = require("body-parser");
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi')
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: true
})
nodeSSPIObj.authenticate(req, res, function(err){
//console.log(res);
res.finished || next()
})
})
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post("/", function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<html>");
res.write("<body>");
res.write("<h1>My Header</h1>");
res.write("<p>My paragraph.</p>");
res.write("<p>Name = " + req.body.user.name + "</p>");
res.write("<p>Email = " + req.body.user.email + "</p>");
res.write("</body>");
res.write("</html>");
res.end();
console.log('End post');
});
// Start server
var port = process.env.PORT || 3000
server.listen(port, function () {
console.log('Express server listening on port %d in %s mode', port, app.get('env'))
})
It turns out the problem went away when I reordered the routing to put the bodyParser lines above the nodeSSPI check.
Specifically, I moved these lines:
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
Above:
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi');
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: false
});
nodeSSPIObj.authenticate(req, res, function(err){
res.finished || next();
});
});

Getting input data from text field in Nodejs

I'm sure this has already been answered but I can't find the exact question I'm looking for.
I have an ejs file that has this for the form.
<form action="" method="POST">
<div class="input-group">
<input type="text" class="form-control" name="userSearchInput" placeholder="Enter the id of the product you would like to buy" aria-label="Recipient's username" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="searchBTN" type="submit"><i class="fas fa-cart-plus mr-2"></i>Add to Cart</button>
</div>
</div>
</form>
On the node side in my app.js file, I've installed and downloaded both express and body-parser and done the requisite require function.
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
I've set up my middleware for body-parser here:
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Then, to get the content of what the user types into the input text box, I'm using this:
app.post('/', function(req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
This is my first time using app.post and since nothing is being console logged- I'm not sure where I'm going wrong.
full app.js file
var express = require('express');
var path = require('path');
var http = require('http');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var nodemon = require('nodemon');
var app = express();
var port = process.env.PORT || 3000;
// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// create connection to mySQL db
var connection = mysql.createConnection ({
host : 'localhost',
user : 'root',
password : 'root',
database : 'bamazon'
});
// initialize connection
connection.connect();
// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
if (error) throw error;
console.log(results);
app.get('/', function(req, res){
res.render('index', {list: results});
})
});
app.post('/', function(req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
// setting up listen for server function
app.listen(port, function (err) {
if (err) throw err;
console.log("Server is running on port " + port);
});
use
<form action="/" method="post">
Firstly add form action in your ejs file like action="/search".Step 2: try with app.post('/search'
Works fine i just commented out db connections only.
may be try this app.js file with new express project.
Run command node app instant of npm start
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
// var nodemon = require('nodemon');
// var mysql = require('mysql');
var app = express();
var port = process.env.PORT || 3000;
// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/*
create connection to mySQL db
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'bamazon'
});
// initialize connection
connection.connect();
// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
if (error) throw error;
console.log(results);
});
*/
app.get('/', function (req, res) {
res.render('index', { list: [], title:"salman" });
})
app.post('/', function (req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
// setting up listen for server function
app.listen(port, function (err) {
if (err) throw err;
console.log("Server is running on port " + port);
});

Invalid Token using expressjs csurf middleware example

I've tried using the expressjs csurf example from https://github.com/expressjs/csurf When using the first example in the Readme, (using Ejs template language), the token validation works fine. When I try using the 'Ignoring Routes' example, on the 'GET /form' to 'POST /process' execution(just as I did in the first example), I get 'invalid token' on the 'POST /process'. The token is being passed to the form on the GET. Any ideas?
Is 'app.use(csrfProtection)' not working? (used in the non working example, if I remove the 'use(csrfP..' and use the methodology from the working example to use the csrf module, IE, passing 'csrfProtection' to the 'get' and 'post' methods, the second example works)
Works:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
app.set('view engine', 'ejs')
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.get('/form', csrfProtection, function(req, res) {
// pass the csrfToken to the view
var tkn = req.csrfToken()
console.log(tkn)
res.render('index', { csrfToken: tkn })
})
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('data is being processed')
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
html/ejs:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
Favorite color: <input type="text" name="favoriteColor">
<button type="submit">Submit</button>
</form>
</body>
</html>
Does not work:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
app.set('view engine', 'ejs')
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
// create api router
var api = createApiRouter()
// mount api before csrf is appended to the app stack
app.use('/api', api)
// now add csrf, after the "/api" was mounted
app.use(csrfProtection)
app.get('/form', function(req, res) {
// pass the csrfToken to the view
var tkn = req.csrfToken()
console.log(tkn)
res.render('index', { csrfToken: tkn })
})
app.post('/process', parseForm, function(req, res) {
res.send('csrf was required to get here')
})
function createApiRouter() {
var router = new express.Router()
router.post('/getProfile', function(req, res) {
res.send('no csrf to get here')
})
return router
}
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app2 listening at http://%s:%s", host, port)
})
In your second example, you are not passing the csrfProtection middleware to the POST processing chain. It should be
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('csrf was required to get here')
})

How to get post params in app.post

I am developing nodejs project. Where I am using ejs with the help of express-helpers module to generate view template html.
in server.js file I have written below code
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var app = express();
var helpers = require('express-helpers')
helpers(app);
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// respond with "index.html" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.render('index.html');
});
app.get('/demo', function (req, res) {
res.render('demo.ejs');
});
app.post('/demo', function (req, res) {
console.log(res.body)
});
I want to know that in app.post how should id get post params
app.post('/demo', function (req, res) {
console.log(res.body)
});
I have tried console.log(req.body) but giving as undefined
Also tried console.log(res.body) but giving as undefined
Let me know how should I implement it?
you should use a middleware such as body-parser
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/demo', function (req, res) {
console.log(req.body)
});
Use the body-parser middleware. First, you need to install it using npm install body-parser. And then use it in your application like this
var bodyParser = require('body-parser');
.....
// For Content-Type application/json
app.use(bodyParser.json());
// For x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
....
app.post('/demo', function (req, res) {
console.log(req.body);
});

Resources