我是这个话题的新手。我想了解更多有关 EJS 的信息。目标是在单击提交按钮后获取我的表单数据。 console.log 中的结果应该是我在表单中插入的数据。除了数据为 NULL 之外,这工作正常。事情就是这样,我就想知道。下面是我的代码。这是我的带有控制器的 server.js 页面的代码片段
我通过单击按钮并执行 AJAX 来获取此 EJS 页面,这里是 onclick = getID(元素的 id) 的代码
function getId(id)
{
// console.log(id)
var request3 = new XMLHttpRequest();
request3.open('GET', `/update`);
request3.setRequestHeader("Content-Type", "application/json");
var body = {
"id": id
}
request3.send();
request3.addEventListener("load", function () {
window.location.href = `localhost:8000/update/${id}`;
})
}
/update/:userId 的终点
app.route("/update/:userId").get(
updatePageControllers)
控制器更新页面控制器
module.exports = async function(req, res)
{
const userId = req.params.userId
try{
res.render("update", {id: userId });
}
catch(err)
{
// console.log(err)
res.json(err);
}
}
我的ejs表单页面/update/:userId
<h1>Updating Id <%= id %></h1>
<form method="post" action="/updateTime/<%= id %>" enctype="multipart/form-data">
<input placeholder="name" name="name"/>
<input placeholder="description" name="description"/>
<input placeholder="price" name="price"/>
<input placeholder="quantity" name="quantity"/>
<input type="file" name="image" accept="image/*"/>
<input type="submit" value="signup"/>
</form>
我期待数据的终点
app.route("/updateTime/:userId")
.post((req,res)=>{
console.log(req.body.name + "yeah")
res.end();
})
要处理
multipart/form-data
请求,您需要使用中间件,例如 multer。
因此,设置 multer,由于您正在上传文件,因此它应该如下所示:
// setup multer
const multer = require('multer');
const upload = multer({...}) // setup
app.route("/updateTime/:userId")
// call multer middleware to process multipart
.post(upload.single('image'), (req,res)=>{
console.log(req.body.name + "yeah")
res.end();
})
解决方案:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ 扩展: true }));
说明:
This line tells Express to parse incoming POST requests with URL-encoded data (like form data) and make the parsed data accessible on the req.body object.
The extended: true option allows parsing of complex nested objects.