Node. js Express Framework POST Method Detailed Explanation
- 2021-07-13 04:19:05
- OfStack
POST method
The following example demonstrates submitting two parameters in a form through the POST method, and we can use the process_post router in the server. js file to process the input:
The code for the index. htm file is modified as follows:
<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
The code for the server. js file is modified as follows:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded Code parsing
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Output JSON Format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log(" Application instance, the access address is http://%s:%s", host, port)
})
Execute the above code:
$ node server.js
Application example, the access address is http://0.0. 0.0: 8081
Browser access http://127.0.0.1: 8081/index. htm