我想了解路由如何与express一起使用。
通过编辑某些代码,我在server.js
const multer = require("multer"); //for uploading image
const bodyParser = require("body-parser"); //for adding employee(below)
app.get("/employees/add", (req, res) => {
res.sendFile(path.join(__dirname, './views', 'addEmployee.html'));
});
app.get("/images/add", (req, res) => {
res.sendFile(path.join(__dirname, './views', 'addImage.html'));
});
app.get("/employees", (req, res) => {
data.getAllEmployees().then((data) => {
res.json(data);
}).catch(function(err) {
console.log("An error was encountered: " + err);
});
});
app.get("/images", (req, res) => {
let imagePath = './public/images/uploaded';
fs.readdir(imagePath, function(err, items) {
if (items.length == 0) {
console.log("No images");
res.send("Error reading images directory<br/><h3>Return to <a href='/'><em>HOME</em></a></h3>");
} else {
//res.json(items);
var finalString = "Images: " + JSON.stringify(items) + "<br/><h3>Return to <a href='/'><em>HOME</em></a></h3>";
res.send(finalString);
}
});
});
const storage = multer.diskStorage({
destination: "./public/images/uploaded",
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
app.use(express.static("./public/images/uploaded"));
app.post("/add-image", upload.single("imageFile"), (req, res) => {
const formFile = req.file;
res.send("<p>Your submission >> " + JSON.stringify(formFile) + " was successful</p><br/><h3>Return to <a href='/'><em>HOME</em></a></h3>");
});
我的data-service.js
有一个定义为
module.exports.addEmployee = function(employeeData) {
return new Promise((resolve, reject) => {
(typeof employeeData.isManager === 'undefined') ? false : true;
employeeData.employeeNum = employees.length + 1;
employees.push(employeeData);
resolve(employees);
});
}
employees
数组位于employees.json
文件中。
我上传图片的工作没有问题。它上传,然后发回给我一个回复。现在,我正在尝试添加新员工以使用body-parser
,但我遇到了一些问题。
我的server.js
等待:
app.get("/employees/add", (req, res) => {
res.sendFile(path.join(__dirname, './views', 'addEmployee.html'));
});
然后重定向到我的addEmployee.html
,其中包含action="/add-employee"
操作,并使用该路线重定向回server.js
app.post("/add-employee", (req, res) => {
//do something
});
我试过用类似的东西来调用它,
app.post("/add-employee", (req, res) => {
data.addEmployee();
//etc
});
已在第二个代码段中定义了addEmployee
。
而且,(显然,否则我不会在这里大声笑),并不是很有效。我觉得,虽然语法可能是一个问题,但我在这里误解了路由逻辑。我错过了什么?