【发布时间】:2021-06-04 19:13:37
【问题描述】:
应用说明:
我正在尝试创建一个 HTML 模板,该模板接受一组卡片对象并使用其中包含的数据来生成一个页面来显示卡片列表。对于此列表中的每张卡片,我应该有一个指向该特定卡片的 URL 的链接(例如,http://localhost:3000/cards/that_card's_id),并且链接文本应指示卡片的名称和唯一的 ID。
基本上,我会在我的 cmd 栏中键入 node server.js,然后打开 google chrome 并在我的地址栏中键入 localhost:3000,它会将我带到显示所有链接的卡片 html 页面。当我点击一张特定的卡片时,它应该会转到另一个 html 页面,该页面只显示显示卡片名称和卡片费用的文本。
问题:
我创建了一个服务器。问题是,当我在地址栏中输入 localhost:3000 时,页面似乎没有加载。我什至无法测试我的代码是否可以正常工作,因为页面不能正常工作完全加载。该页面只显示“此页面不工作”和“本地主机没有发送任何数据”。有人告诉我这是因为在我的服务器代码中,我正在监听请求网址 /cards 、 /cards/ 和 /cards? 。当我尝试访问 localhost:3000 时,请求 url 是 / ,所以我试图访问一个我没有处理的 url。
server.js:
const pug = require("pug");
const fs = require("fs");
const http = require("http");
const url = require('url')
let cardData = require("./cards.json");
let cards = {};
cardData.forEach(card => {
cards[card.id] = card;
});
//Initialize server
const server = http.createServer(function(request, response) {
if (request.method === "GET") {
if (request.url === "/cards") {
response.statusCode = 200;
response.write(pug.renderFile("./views/cards.pug", { cards: cards }));
response.end();
}else if (request.url.startsWith("/cards/")) {
const paths = request.url.split("/");
const cardId = paths[2];
if (cards.hasOwnProperty(cardId)) {
const targetCard = cards[cardId];
response.statusCode = 200;
response.write(
pug.renderFile("./views/card.pug", { card: targetCard })
);
response.end();
return;
} else {
response.statusCode = 404;
response.end();
return;
}
} else if (request.url.startsWith("/cards?")) {
const params = request.url.split("?");
const [_, value] = params[1].split("=");
const limit = parseInt(value);
if (limit < 1) {
response.statusCode = 400;
response.write("Invalid query");
response.end();
return;
}
const responseCards = Object.values(cards).slice(0, limit);
response.statusCode = 200;
response.write(
pug.renderFile("./views/cards.pug", { cards: responseCards })
);
response.end();
return;
}
} else {
response.statusCode = 404;
response.write("Unknown resource.");
response.end();
}
});
//Start server
server.listen(3000);
console.log("Server listening at http://localhost:3000");
cards.json:
[
{
"artist":"Arthur Bozonnet",
"attack":3,
"collectible":true,
"cost":2,
"flavor":"And he can't get up.",
"health":2,
"id":"AT_003",
"mechanics":["HEROPOWER_DAMAGE"],
"name":"Fallen Hero",
"rarity":"RARE"
},
{
"artist":"Dan Scott",
"attack":3,
"collectible":true,
"cost":4,
"flavor":"Is he aspiring or inspiring? Make up your mind!",
"health":5,
"id":"AT_006",
"mechanics":["INSPIRE"],
"name":"Dalaran Aspirant",
"rarity":"COMMON"
}
]
cards.pug:
html
head
title Cards
body
div#main
h1 List of Cards:
each card in cards
a(href="/cards/" + card.name) #{card.id}
br
card.pug:
html
head
title #{card.name}
body
div#main
h1 Name: #{card.name}, Cost: $#(card.cost)
【问题讨论】:
-
请尽量保持问题陈述简洁明了。不宜过长
标签: javascript node.js json server localhost