我正在使用 node.js、MySql、Express 和 Pug 创建鸡尾酒网站和数据库。
我最近尝试使用路由参数,以便不同的鸡尾酒有不同的 URL,而不是通过 get 传递名称。所以 URL 应该是“localhost:3000/cocktail/Cosmopolitan”而不是“localhost:3000/cocktail?name=Cosmopolitan”。问题是我的 get 路线似乎被调用了两次。一次使用正确的参数“Cosmopolitan”,然后再次使用参数“style.css”,这导致站点显示时没有任何样式,并且输出中的 TypeError 进一步下降。
我的鸡尾酒路线目前是这样的:
const Router = require('express-promise-router');
const db_func = require("../database/db_functions");
const router = new Router();
router.get("/:name", async (req, res) => {
var name = req.params.name;
console.log(req.params);
const cocktail = await db_func.getCocktail(name);
const ingredients = await db_func.getIngredientById(cocktail["id"]);
console.log(ingredients);
await res.render('cocktail', {
cocktail: cocktail,
ingredients: ingredients
});
});
module.exports = router;
现在的问题是这个输出
{ name: 'Cosmopolitan' }
[
RowDataPacket { name: 'Wodka', amount: 5, measure: 'cl', garnish: 0 },
RowDataPacket {
name: 'Limettensaft',
amount: 2,
measure: 'cl',
garnish: 0
},
RowDataPacket {
name: 'Cointreau',
amount: 2,
measure: 'cl',
garnish: 0
},
RowDataPacket {
name: 'Cranberrynektar',
amount: 2,
measure: 'cl',
garnish: 0
}
]
{ name: 'style.css' }
TypeError: Cannot read property 'id' of undefined
at F:\Arbeit und Studium\Projects\Cocktail Database\Cocktail Node\routes\cocktail.js:10:65
at processTicksAndRejections (internal/process/task_queues.js:97:5)
对应的pug文件。鸡尾酒.哈巴狗:
extends layouts/layout
block content
h4.random-title #{cocktail.name}
p Served in a #{cocktail.glass} Glass!
div.ingredient-list
- for (var i = 0; i < ingredients.length; i++)
p - #{ingredients[i].amount} #{ingredients[i].measure} #{ingredients[i].name}
p Recipe by: #{cocktail.author}
和layouts/layout.pug
doctype html
html
head
title Cocktailbar
link(rel="stylesheet" type="text/css" href="style.css")
body
div.page-container
...
如有任何意见,我将不胜感激!
最佳答案
好吧,Chris 建议的问题是我的 style.css 位于 public/style.css 而不是单独的文件夹中。
此外,我将样式表链接到 style.css 而不是/style.css,或者更好的是/css/style.css,从而访问 localhost:3000/cocktail/style.css 上的网站并触发我的路线。
关于javascript - Express router 将 style.css 作为 request.params 传递并且可能调用路由两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63044698/