所以我仍然是nodejs的初学者,当我在浏览器中运行http://127.0.0.1:3000/时,我得到此消息Cannot GET /
,这是因为我使用了switch语句。我不能在app.get
内使用开关吗?我想使代码DRY,这就是我使用开关的原因。
const express = require('express');
const app = express();
const port = 3000;
const hostname = 'localHost';
app.get('/:main/:sub/:sub2', (req, res) => {
let main = String(req.params.main).toLowerCase();
let sub = String(req.params.sub).toLowerCase();
let sub2 = String(req.params.sub2).toLowerCase();
switch (main) {
case "":
res.send(`Hi there welcome to my assignment`);
case "speak":
{
switch (sub) {
case "pig":
res.send(`The pig says 'Oink'`);
case "cow":
res.send(`The cow says 'Moo'`);
case "dog":
res.send(`The dog says 'Woof Woof!'`);
case "*":
res.send(`sorry no one speaks here!`);
}
}
case "repeat":
{
if (sub2 === !NaN) {
for (let i = 0; i < sub2; i++) {
res.send(`${sub}`);
}
}
}
default:
res.send(`Page not found!`);
}
});
app.listen(port, hostname, () => {
console.log(`server has started`)
});
答案 0 :(得分:1)
您的空字符串大小写不是有效的参数,无法在main
中进行搜索。
使用app.get
创建默认路由:
const express = require('express');
const app = express();
const port = 3000;
const hostname = 'localHost';
app.get("/", (req, res) => res.send("Welcome to my assignment"));
app.get('/:main/:sub/:sub2', (req, res) => {
let main = String(req.params.main).toLowerCase();
let sub = String(req.params.sub).toLowerCase();
let sub2 = String(req.params.sub2).toLowerCase();
switch (main) {
case "speak":
{
switch (sub) {
case "pig":
res.send(`The pig says 'Oink'`);
break;
case "cow":
res.send(`The cow says 'Moo'`);
break;
case "dog":
res.send(`The dog says 'Woof Woof!'`);
break;
case "*":
res.send(`sorry no one speaks here!`);
break;
}
}
case "repeat":
{
if (!Number.isNaN(sub2)) {
let str = "";
for (let i = 0; i < sub2; i++) {
str+=sub;
}
res.send(str);
}
break;
}
default:
res.send(`Page not found!`);
break;
break;
}
});
app.listen(port, hostname, () => {
console.log(`server has started`)
});
编辑,我还调整了“重复”功能,使其正常工作。 !NaN
始终为true
。您的原始代码基本上说if(sub2 === true)
,但从来没有。我使用!Number.isNaN
条件方法进行了修改。然后,我将一个字符串连接起来并输出n
次。