三.node.js中獲取post請求的兩種方式


  • 方式一:通過綁定數據流data事件來獲取
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="login" method="post">
        username: <input type="text" name="username"><br>
        password: <input type="password" name="password"><br>
            <input type="submit" value="Sign in">
    </form>
</body>
</html>
const express = require("express");

const app = express();

app.listen(8080);


//引入querystring,將字符串轉換成對象
const querystring = require("querystring");

//調轉到登錄頁面
app.get("/login.html",(req,res)=>{
    console.log(__dirname+"/static/login.html");
    res.sendFile(__dirname+"/static/login.html");
})

//post請求,獲取post請求中的數據
app.post("/login",(req,res)=>{
    req.on("data",myData=>{
        console.log(querystring.parse(myData.toString()));
    })
})
  • 方式二:使用中間件獲取
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="reg" method="post">
        username: <input type="text" name="username"><br>
        password: <input type="password" name="password"><br>
            <input type="submit" value="Sign in">
    </form>
</body>
</html>
const express = require("express");

const app = express();

app.listen(8080);

//處理req騎牛攜帶數據的中間件,將req的數據局放在req.body的屬性上
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
   extended:true
}))

//調轉到注冊頁面
app.get("/reg.html",(req,res)=>{
    res.sendFile(__dirname+"/static/reg.html");
})

//第二種方式獲取post請求中的數據
app.post("/reg",(req,res)=>{
    //獲取post請求參數
    const {username,password} = req.body;
    console.log(username,password);
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM