46.Express框架 GET 方法和POST 方法
生活随笔
收集整理的這篇文章主要介紹了
46.Express框架 GET 方法和POST 方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
轉(zhuǎn)自:http://www.runoob.com/nodejs/nodejs-express-framework.html
GET 方法
以下實(shí)例演示了在表單中通過(guò) GET 方法提交兩個(gè)參數(shù),我們可以使用 server.js 文件內(nèi)的?process_get?路由器來(lái)處理輸入:
index.htm 文件代碼:
<html> <body> <form action="http://127.0.0.1:8081/process_get" method="GET"> 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>?
server.js 文件代碼:
var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.get('/process_get', function (req, res) { // 輸出 JSON 格式 var response = { "first_name":req.query.first_name, "last_name":req.query.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("應(yīng)用實(shí)例,訪問(wèn)地址為 http://%s:%s", host, port) })執(zhí)行以上代碼:
node server.js 應(yīng)用實(shí)例,訪問(wèn)地址為 http://0.0.0.0:8081瀏覽器訪問(wèn) http://127.0.0.1:8081/index.htm,如圖所示:
現(xiàn)在你可以向表單輸入數(shù)據(jù),并提交,如下演示:
POST 方法
以下實(shí)例演示了在表單中通過(guò) POST 方法提交兩個(gè)參數(shù),我們可以使用 server.js 文件內(nèi)的?process_post?路由器來(lái)處理輸入:
index.htm 文件代碼:
<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>?
server.js 文件代碼:
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // 創(chuàng)建 application/x-www-form-urlencoded 編碼解析 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) { // 輸出 JSON 格式 var 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("應(yīng)用實(shí)例,訪問(wèn)地址為 http://%s:%s", host, port) })執(zhí)行以上代碼:
$ node server.js 應(yīng)用實(shí)例,訪問(wèn)地址為 http://0.0.0.0:8081瀏覽器訪問(wèn) http://127.0.0.1:8081/index.htm,如圖所示:
現(xiàn)在你可以向表單輸入數(shù)據(jù),并提交,如下演示:
轉(zhuǎn)載于:https://www.cnblogs.com/sharpest/p/8072809.html
總結(jié)
以上是生活随笔為你收集整理的46.Express框架 GET 方法和POST 方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 47.2. 配置 Tomcat 服务器
- 下一篇: ssm整合(基于xml配置方式)