Empty body when submitting html form

时间:2018-03-25 20:35:09

标签: javascript node.js

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

2 个答案:

答案 0 :(得分:3)

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}));

答案 1 :(得分:1)

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