简体   繁体   中英

How to get post data from html form in nodes with express4?

Below is my main.js file

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var userAPI = express.Router();

app.use(express.static(__dirname + '/public'));
app.use( bodyParser.json() );

userAPI.post('/mydir/hello', function(req, res){
  console.log("hi");
  console.log(req.body.name);
  console.log(req.body.country);
  res.send('Name: ' + req.body.name);
  res.send('Name: ' + req.body.country);
  res.end();
});

app.use('/', userAPI);
app.listen(12345);

and here is my test_post_method.html form

<form action="/mydir/hello" method=""POST">
    name: <input type="text" name="name"/><br/>
    country: <input type="text" name="country"/>
    <input type="submit"/>
</form>

When I go to http://localhost:12345/test_post_method.html , I can see the form and input "test for name" and "1234 for country for country" to test.

Then I click submit and only got this message

Cannot GET /mydir/hello?name=test&country=1234

Did I do something wrong?

HTML forms do not send JSON.

You need bodyParser.urlencoded() .

You also need to tell the HTML to send a POST, without a syntax error.

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