我正在嘗試輸出title我在/Add-Product鏈接中的表單中輸入的值
這是我的 app.js 代碼
const http= require('http');
const path= require('path');
const express= require('express');
const app= express();
app.set('view engine', 'ejs');
app.set('views', 'Views');
app.use(express.static(path.join(__dirname, 'Public')));
app.get('/', (req, res, next)=>{
res.render('shop');
});
app.get('/admin', (req, res, next)=>{
res.render('admin');
});
app.get('/add-product', (req, res, next)=>{
res.render('addProduct');
});
app.post('/add-product', (req, res, next)=>{
console.log(req.body.title); //uable to display value of req.body.title
res.redirect('/');
});
app.listen(3000);
構成 addProduct.ejs 的一部分
<main>
<form action="/add-product" method="POST">
<p>Title</p>
<input type="text" name="title" id="title"/>
<p>Price</p>
<input type="text" name="price"/>
<p>Description</p>
<input type="text" name="description"/>
<button type="submit">Submit</button>
</form>
</main>
無法弄清楚為什么 req.body.title 會拋出一個錯誤:Cannot read property 'title' of undefined
請指導我了解我遺漏了什么。
uj5u.com熱心網友回復:
默認情況下,表單以application/x-www-form-urlencoded. 所以需要配置node js來接收這種型別的內容。使用bodyParser與JSON和編碼的內容讀取請求體。
用法:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/374070.html
上一篇:如果執行時間超過20秒,如何中斷nodejsfor回圈?
下一篇:用陣列過濾貓鼬陣列?
