node學習筆記(三)創建一個post請求

post請請求和get請求不一樣。express框架中想要直接取到post傳值,需要藉助中間件body-parser。

body-parser是一個HTTP請求體解析的中間件,使用這個模塊可以解析JSON、Raw、文本、URL-encoded格式的請求體。

js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());//數據JSON類型
app.use(bodyParser.urlencoded({ extended: false }));//解析post請求數據

app.all('*',function(req,res,next){  
 let origin=req.headers.origin;
   res.setHeader('Access-Control-Allow-Origin',"*");//解決跨域
   res.setHeader('Access-Control-Allow-Headers','Content-Type');
    next();
})
app.post('/login',(req,res)=>{
    console.log(req.body)
    res.send('登錄成功')
})
app.listen(3000,()=>{
    console.log('Express web app on http://localhost:3000')

})
 

html:

<form method="post" action="http://localhost:3000/login">
    <input name="username" type="text">
    <br>
    <input name="password" type="text">
    <input type="submit" value="Submit">
</form>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章