Node.js - Localhost didn't send any data / server not loading

Application desc:

I’m trying to create an HTML template which takes in an array of card objects and uses the data contained within to generate a page to display the list of cards. For each card in this list, I’m supposed to have a link that points to the URL for that specific card (e.g., http://localhost:3000/cards/that_card’s_id) and the link text should indicate the card’s name and unique ID.

Basically, I would type node server.js in my cmd bar and then open google chrome and type localhost:3000 in my address bar, and it would take me to the cards html page which displays all the links. When I click on a specific card, it should take me to another html page that just displays text showing the card name and cost of the card.

Problem :

I created a server. The problem is, when I type in localhost:3000 in my address bar, the page doesn’t seem to load. I can’t even test to see if my code works as the page doesn’t load at all. The page just says “This page isn’t working” and “localhost didn’t send any data.” I was told it’s because in my server code, I’m listening for request urls /cards , /cards/ and /cards? . When I try to access localhost:3000 , the request url is / , so I am trying to access a url that I am not handling.

I was wondering how I would fix this issue? Should I be putting “/cards.pug” or something? I don’t have an HTML page file either to direct to, I’m trying to load any page that starts with the cards or card keyword. I’ve seen examples where it’s just like localhost:3000/cards/ and that’s the address I want the cards.pug page to load as. When I click on a specific card link it should go to the card.pug page and the address would be something like localhost:3000/cards/AT_003/ with the last bit being that specific card’s id. The ids are found in the json file, and AT_003 would be the id for the first card link. So basically, if I were to click on the first card link called “Fallen Hero (AT_003)”, the address should be localhost:3000/cards/AT_003/

Is there a way to extract the id from each card to insert into my url? I have hundreds of cards that are not included in this post, and I would prefer not to hardcode it. If a card with the requested ID does not exist, I would like to respond with a 404 error, but the thing is I don’t even know how to check for the id/get the id for each card url.

Note: The cards.pug and card.pug files are located in a folder called ‘views’, which it’s included in the paths ./views/card.pug", etc.

Any help would be appreciated!

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)

What the cards.pug page should look like:

Is there a reason why you’re not using something like express?

I haven’t learned express yet unfortunately, although I do plan to learn soon! Right now I’m just figuring out how to get a server to run properly - but express is allowed for this task. I just don’t have much knowledge of it yet so I’ve been trying to attempt this with node.js

I’ve personally never used templating engines outside of express (and quick google search didn’t find anything relevant).
My advice would be to learn the basics of express and use it for your task. You’ll save a ton of time.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.