我正在使用 NodeJS 和 Express(資料庫使用 SQL/MySQL)創建一個 JS Web 應用程式,幾乎直接實作了這個 API 教程:https ://www.bezkoder.com/node-js-rest-api-express- mysql/(只是將 'tutorials' 替換為 'Employees')。
我正在嘗試撰寫 API 函式來獲取具有特定屬性的所有員工(在 SQL 表中),例如所有具有 lastName = "Garcia" 的員工或所有具有 teamID = 43682 的員工等。
在我的 routes.js 檔案中,我有這個:
module.exports = app => {
const employees = require("../controllers/employee.controller.js");
const router = require("express").Router();
// Create a new Employee
router.post("/", employees.create);
// Retrieve all Employees
router.get("/", employees.findAll);
// Retrieve all Employees with lastName
router.get('/', employees.findLastName);
... a bunch more CRUD functions ...
app.use('/api/employees', router);
};
這是相應的控制器功能:
exports.findLastName = (req, res) => {
const lastName = req.query.lastName; // tried changing req.query.lastName to req.params.lastName
Employee.getLastName(lastName, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Error occurred while retrieving by last name."
});
else {
console.log(`Employees with lastName ${lastName} were found!` );
res.send(data);
}
});
};
exports.findAll = (req, res) => {
const title = req.query.title;
Employee.getAll(title, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while retrieving employees."
});
else {
console.log(`Employee with ${title} title was found!` );
res.send(data);
}
});
};
findAll 路由/函式(剛剛從該教程復制)通過查找具有特定 ID 號(資料庫中的主鍵)的所有員工來作業,我知道通過 Postman 對其進行測驗可以作業。我通過復制 findAll 函式并將其更改為按 lastName 搜索來撰寫 findLastName 路由/函式,并在模型和控制器類中制作相應的函式。
新函式 findLastName 不起作用……除非我將路由放在findAll 路由之前(或將其注釋掉)。然后它正確呼叫我的所有函式并回傳所有帶有 lastName 引數的員工。
這里到底發生了什么?您是否不允許擁有多個 .get() 路線之類的?如果是這樣,我將如何實作這樣的搜索 API?這是我第一次構建這樣的網路應用程式,所以不可否認,我對路由和所有這些作業的方式仍然有些模糊。謝謝你的幫助!
uj5u.com熱心網友回復:
在 Express 中,只要第一個路由匹配第二個,就會被忽略,因此在您的場景中,您有兩個route.get具有相同路徑/
router.get('/', employees.findAll);
//Since route with path `/` is matched above already this will be ignored
router.get('/', properties.findLastName);
為了找到姓氏的員工,您需要使用引數創建一個新路線(引數將包含姓氏)
router.get('/:lastName', properties.findLastName);
您可以req.params.lastName在控制器中訪問這樣的引數值
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/532144.html
上一篇:微服務通信模型
