简体   繁体   中英

Empty body when submitting html form

I have a simple NodeJs app, and trying to build a simple authentification form. But for some reason, i'm not able to get the entred data in the form. Here's my code :

var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser= require ('body-parser');
var user = require('./routes/user');
var login = require('./routes/login');
var jwt = require('jsonwebtoken');

var app = express();
app.use(bodyParser.json());
app.use(cookieParser());


app.get('/userprofile', user.getUserInfos);
app.post('/users', user.createUser);
app.get('/login', function (req, res) {
    var html='';
    html +="<body>";
    html += "<form action='/login'  method='post' name='logingorm' enctype=\"application/json\">";
    html += "Username:<input type= 'text' name='username'><br>";
    html += "Password:<input type='password' name='password'><br>";
    html += "<input type='submit' value='submit'>";
    html += "</form>";
    html += "</body>";
    res.send(html);
});
app.post('/login', user.login);


app.listen(3000);
console.log('Listening on port 3000...');

And then, the login function called when a post is received on /login :

exports.login= function(req, res) {
    console.log(req.body);
}

Always get {} as result of my console.log

Any idea ?

Thanks a lot

application/json is not a valid form encoding. When the browser sees that, it falls back to application/x-www-form-urlencoded . bodyParser.json() ignores requests with MIME types other than application/json , and even if it didn't, it wouldn't be able to parse the urlencoded data. Use bodyParser.urlencoded() instead.

app.use(bodyParser.urlencoded({extended: false}));

I think that might be because there is no 'value' attribute written for both the input tags. Try writing them and check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM