Express.js POST请求基础教程文档
收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體
Express.js POST请求
GET和POST都是用于构建REST API的两个常见HTTP请求。 POST请求用于发送大量数据。
Express.js可帮助您使用express实例处理GET和POST请求。
Express.js POST方法
Post方法可帮助您发送大量数据,因为数据是在正文中发送的。发布方法很安全,因为数据在URL栏中不可见,但没有像GET方法那样普遍使用。另一方面,GET方法比POST更有效并且使用更多。
让我们以一个示例来演示POST方法。
示例1:
以JSON格式获取数据
文件: Index.html
<html> <body> <form action="http://127.0.0.1:8000/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>
文件: post_example1.js
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // Create application/x-www-form-urlencoded parser var urlencodedParser = bodyParser.urlencoded({ extended: false }) app.use(express.static('public')); app.get('/index.html', function (req, res) { res.sendFile( __dirname + "/" + "index.html" ); }) app.post('/process_post', urlencodedParser, function (req, res) { // Prepare output in 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(8000, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) })
打开页面index.html并填写条目:
现在,您将以JSON格式获取数据。
注意: 在上图中,您可以看到与GET方法不同,URL栏中的条目不可见。