首先,我感谢您阅读并尝试解决我的问题。
我动态渲染了我的 {dropdown},但我无法在后端获取所选值。
在我的表单上,我还获得了照片,并且套件的名称是动态呈现的。
如果我做错了什么,请使用下面的代码。
Lang - JavaScript FW-Express Js 模板-EJS
我有 body-parse 并设置为 true。
问题是我无法使用 POST 请求(未定义或 null)将所选值发送到后端。
但是如果我使用 GET 作为操作和请求,我确实会获得所选值。
再次感谢您。如果我不清楚,我会解释清楚。我是新的 NODE JS 和 EXPRESS。
-前端
<form class="ui form" action="admin/uploadphoto" method="POST" enctype="multipart/form-data">
<h2 class=" ui dividing header" style="text-align: center;">Add Images to suites</h2>
<div class="two fields">
<div class="field">
<label>Add Suites Images</label>
<input name="suiteimage" type="file">
</div>
<div class="field">
<label>Suites*</label>
<select name="suiteselected" class="ui dropdown">
<% suites.forEach(function(suite) { %>
<option name = "suiteid" value="<%= suite.suite_name %>"><%= suite.suite_name %></option>
<% })%>
</select>
</div>
</div>
<input type="submit" class="ui button" tabindex="0" value="Save New Suite">
</form>
- 后端
const uuid = require("uuid/v4");
const { Pool } = require("pg");
const multer = require("multer");
// Insert photo and selected value from dropdown (options)
const PostPhoto = (req, res) => {
var suiteimage;
const suite_photo_id = uuid();
const {suiteselected} = req.body;
console.log( suiteselected + " --ID") //Here i am testing if selected valued is passed
// this is my multer function to config where i need to store my photo path
upload(req, res, err => {
suiteimage = req.file.path;
if (err) {
console.log(err);
} else {
console.log(suiteimage);
}
});
..... //my database query to save my post....
};
-路线
router.post ('/uploadphoto', service.PostPhoto);
``
最佳答案
我已经找到了解决方案,应该需要 body-parse 并将其扩展为 true。
当将文本和图像作为 1 个表单发布到后端时,请确保
- 您的图像函数(上传)位于 req,res 函数内,否则值将是 undefine 或 null。
如果您需要更多解释请评论。
//my post for image and text function
const PostPhoto = (req, res) => {
const suite_photo_id = uuid();
upload(req, res, function(err) {
const {suiteselected} = req.body;
console.log(req.file);
var imagePath = req.file.path.replace(/^public\//, '');
console.log( suiteselected + " --ID")
console.log(imagePath);
pool.query(
"INSERT INTO suite_photos (suite_photo_id,suite_photo,suite_id) VALUES($1,$2,$3)",
[suite_photo_id, imagePath,suiteselected],
(error, result) => {
if (error) {
throw error;
} else{
console.log(result);
res.redirect("/admin");
}
}
);
});
};
这就是所有的改变。
谢谢大家!!!
关于javascript - 如何从动态生成的 <option> <select> Express ejs 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59842861/