[英]express nodejs POST request form input method
有人能幫我理解為什么我的身體是空的嗎?
文檔上說 express.json() 使用 body-parser 所以它與我使用 express.json() 或 bodyParser() 是一樣的嗎?
在文檔上還說我可以通過 json 對象選項上的選項設置提供標題的類型......我認為它是這樣的:
app.use(express.json({ type: 'application/json' }))
我的標題內容類型說: 'content-type': 'application/x-www-form-urlencoded' 默認是“application/json”,正如文檔所說。
我需要將表單值作為 json 取回,以便我可以節省數據庫和內容。
好吧,我想通了。
整個問題出在 html 輸入上。 不是解析器配置。
問題是,例如,當您通過郵遞員發送某些內容時,如果您想發送 application/x-www-form-urlencoded 類型,郵遞員將為您提供一個界面來設置鍵值對。 如果您使用原始 json 與“應用程序/json”相同,我認為您將必須設置一個有效的 json,並帶有鍵值對。
在郵遞員上,如果您在不提供值的鍵的情況下發送任何一個,則 req.body 將導致為空,如 express 在文檔中所述
“在中間件之后的請求對象上填充包含解析數據的新正文對象(即 req.body),或者如果沒有正文要解析,則內容類型不匹配,則為空對象 ({}),或發生錯誤。”
我從來不明白 html 輸入和東西上“名稱”屬性的原因。 好吧,我謙虛地認為這就是價值(我還沒有搜索過)。
解決方案是在輸入上設置 name 屬性 =>
身體的響應是 => name:'... 輸入的任何內容...'
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/" , method="POST">
<!-- <input type="text" id="name" name="name" placeholder="name" required> -->
<input type="text" name="name"> // name attribute is the key "name" for your input.
<input type="text" name="age"> // name attribute is the key "age" for your attribute.
<input type="submit">
</form>
</body>
</html>
javascript:
const express = require('express')
const path = require('path')
const app = express()
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.get('/', (req, res) => {
res.sendFile('index.html', { root: path.join(__dirname) })
})
app.post('/', (req, res) => {
console.log(req.body) // the result is the input value.
})
app.listen(3000, () => {
console.log('working')
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.