Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

LAB | Express Basic Server

Learning Goals

This exercise allows you to practice and apply the concepts and techniques taught in class.

Upon completion of this exercise, you will be able to:

  • Set up a TypeScript project that uses Express, and initialize package.json and tsconfig.json
  • Install Express.js and its TypeScript types using npm
  • Use the import syntax to import packages and JSON files
  • Use an npm script with tsx to run the server in development mode
  • Create a simple HTTP server using Express.js
  • Set up middleware in Express.js to perform additional request processing such as logging, serving static files, etc.
  • Implement server routes that handle GET HTTP requests and send text and JSON responses
  • (Bonus) Read dynamic values from the URL using req.params and req.query


Introduction

In this lab, we're diving into practical application with ExpressJS and TypeScript. You'll be setting up a basic server to host a personal blog with a projects showcase section - something that every developer needs. In each iteration, we will guide you in setting up the app and defining routes, resulting in a fully functional server and a personal blog website. Let's get started!

Example - Finished LAB


Setup

  • Fork this repo
  • Clone this repo
  • Open the LAB and start
cd lab-express-basic-server-ts

Submission

  • Upon completion, run the following commands:
git add .
git commit -m "done"
git push origin master
  • Create a Pull Request and submit your assignment

Instructions

Try your best to solve each iteration on your own before checking the solution. Nevertheless, if you find yourself stuck, feel free to check the provided solution as a reference to help you solve the iteration.


Iteration 0 | Set up the project

To set up the project for an Express server with TypeScript, follow the below steps.


1. Initialize npm:

  • Run npm init -y to create a package.json file.

2. Install dependencies:

  • Run npm install express morgan to install the Express and Morgan packages.
  • Run npm install --save-dev @types/express @types/morgan to install the TypeScript types for both packages as dev dependencies.

3. Create the tsconfig.json file:

  • In the root of the project, create a file named tsconfig.json and add the following compiler options:

    {
      "compilerOptions": {
        "target": "es2025",
        "module": "NodeNext",
        "strict": true,
        "outDir": "./dist",
        "esModuleInterop": true,
        "resolveJsonModule": true
      }
    }

    The resolveJsonModule option allows you to import .json files in your TypeScript code. You will need it later in this lab to import the data from the data/ folder.


Iteration 1 | Add the npm Scripts

Next, set up the npm scripts you will use to build and run your server.


1. Install tsx:

  • Run npm install --save-dev tsx to install tsx as a dev dependency. tsx runs TypeScript files directly and restarts the server every time you save a change.

2. Add the scripts:

  • Update the package.json -> "scripts" section to include the following scripts:

    "scripts": {
      "build": "tsc",
      "start": "node dist/app.js",
      "dev": "npx tsx watch app.ts"
    },

From now on, you will start your server with npm run dev. You will do that in the next iteration, once the server code is in place.


Iteration 2 | Create Express Server

Next, you should create an Express server in app.ts and set up basic middleware. Follow the comments in the app.ts file and do the following:

  • Import the express package using import
  • Import the morgan package using import
  • Create the Express app
  • Set up the following middleware that you will need for your Express server:
    • morgan logger for logging the incoming requests
    • express.json() to parse incoming requests with JSON payloads
  • Create a route handler for GET / that responds with a simple text message, such as "The server is working!"
  • Set up the Express server to listen on port 5005

Note: Don't add the express.static() middleware yet. You will add it in the next iteration.


Start the server by running the following command:

npm run dev

To test the server, navigate to localhost:5005/ in your browser.
If everything is set up correctly, you should see your message in the browser, and the request logged by morgan in the terminal.


Solution
// IMPORT PACKAGES
import express from 'express';
import logger from 'morgan';

// CREATE EXPRESS APP
const app = express();

// MIDDLEWARE
app.use(logger('dev'));
app.use(express.json());

// ROUTES
app.get('/', (req, res) => {
  res.send('The server is working!');
});

// START THE SERVER
app.listen(5005, () => console.log('Server listening on port 5005'));



Iteration 3 | Serve the Static Files

Now let's make the server send the HTML pages of the website, together with their styles and images.


1. Organize the project files:

  • In the root of the project, create a public/ folder that will hold all the static files of the website.
  • Move the provided HTML files home.html and blog.html into the public/ folder.
  • Move the provided styles.css and profile.png files into the public/ folder.

2. Set up the static middleware:

  • In app.ts, set up the express.static() middleware to serve the static files from the public folder. Add it after the morgan logger and before express.json().

To test it, navigate to each of the following URLs in your browser and check that every page is sent, with its styles and images:


Note: The My Projects section of the home page and the articles list of the blog page will show an error message for now. These pages request their data from the server, and you will create the routes that send it in the next iterations.


Solution
// MIDDLEWARE
app.use(logger('dev'));
app.use(express.static('public'));
app.use(express.json());



Iteration 4 | JSON Data for Projects

Create a route GET /api/projects that responds back with the JSON data from the file data/projects.json.
The purpose of this route is to provide the JSON data for the home.html page, which requests and renders it in the My Projects section as a list.

You will need to import the file data/projects.json in app.ts. To import a JSON file, add with { type: 'json' } at the end of the import statement:

import projects from './data/projects.json' with { type: 'json' };

To test the route, navigate to localhost:5005/api/projects in your browser.
If you set up the route correctly, you should see the JSON data with projects sent in the response.

Then, reload localhost:5005/home.html. The My Projects section should now show the list of projects instead of the error message.


Solution
// IMPORT DATA
import projects from './data/projects.json' with { type: 'json' };

// ...

// ROUTES
app.get('/api/projects', (req, res) => {
  res.json(projects);
});



Iteration 5 | JSON Data for Articles

Create a route GET /api/articles that responds back with the JSON data from the file data/articles.json.
The purpose of this route is to provide the JSON data for the blog.html page, which requests it to render the articles list.

You will need to import the file data/articles.json in app.ts.


To test the route, navigate to localhost:5005/api/articles in your browser.
If you set up the route correctly, you should see the JSON data with articles sent in the response.

Then, reload localhost:5005/blog.html. The blog page should now show the list of articles instead of the error message.


Solution
// IMPORT DATA
import articles from './data/articles.json' with { type: 'json' };

// ...

// ROUTES
app.get('/api/articles', (req, res) => {
  res.json(articles);
});



Bonus: Iteration 6 | Get One Project with req.params

Create a route GET /api/projects/:index that responds back with the single project found at that position (index) of the projects array.

For example, localhost:5005/api/projects/0 should respond with the first project, Blackjack Game.

If there is no project at that index, for example localhost:5005/api/projects/99, respond with the status code 404 and a JSON message such as { "message": "Project not found" }.


Note: Route params are always strings. To use req.params.index as an array index in TypeScript, you will need to convert it to a number with Number().


Solution
app.get('/api/projects/:index', (req, res) => {
  const project = projects[Number(req.params.index)];

  if (!project) {
    res.status(404).json({ message: 'Project not found' });
    return;
  }

  res.json(project);
});



Bonus: Iteration 7 | Filter Articles with req.query

Update the GET /api/articles route so it accepts an optional tag query. When the tag query is present, the route should respond only with the articles whose tags array includes that tag. When it is not present, the route should keep responding with all the articles.

To test the route, navigate to the following URLs in your browser:


Note: TypeScript doesn't know that req.query.tag holds a string, because query values can also come in other formats. Use as string to tell TypeScript to treat it as a string.


Solution
app.get('/api/articles', (req, res) => {
  if (!req.query.tag) {
    res.json(articles);
    return;
  }

  const filteredArticles = articles.filter((article) => {
    return article.tags.includes(req.query.tag as string);
  });

  res.json(filteredArticles);
});



Happy coding! 💙


FAQs

I am stuck and don't know how to solve the problem or where to start. What should I do?

If you are stuck in your code and don't know how to solve the problem or where to start, you should take a step back and try to form a clear question about the specific issue you are facing. This will help you narrow down the problem and come up with potential solutions.

For example, is it a concept that you don't understand, or are you receiving an error message that you don't know how to fix? It is usually helpful to try to state the problem as clearly as possible, including any error messages you are receiving. This can help you communicate the issue to others and potentially get help from classmates or online resources.

Once you have a clear understanding of the problem, you will be able to start working toward the solution.


Back to top

I got the error "Cannot find module './data/projects.json'. Consider using '--resolveJsonModule' to import module with '.json' extension". How do I fix it?

TypeScript doesn't allow importing .json files by default. To enable it, make sure your tsconfig.json includes the resolveJsonModule option in compilerOptions:

"resolveJsonModule": true

Also check that the import statement ends with with { type: 'json' } and that the file path is correct:

import projects from './data/projects.json' with { type: 'json' };

Back to top

I got the error: "Cannot find module" Node.js". How can I resolve it?

The error "Cannot find module" in a Node.js application means that the module you are trying to import or use does not exist in your project or cannot be found by Node.js.

There are a few things you can try to resolve the issue:

  1. Dependencies are not installed: Make sure that all dependencies are installed.
To do this, run the command `npm install` in the root folder of your project.
This will install all of the dependencies listed in the project's `package.json` file, and ensure that all of the modules that your Node'js application requires are available.
  1. Module is not installed: Make sure that the package you are trying to use is listed in the project's package.json and that it is installed.
To do this, run the command `npm install <package_name>`, replacing the `<package_name>` with the name of the package.
This will add the package to the list of dependencies in the `package.json` file, and install it in the project.
  1. Module is not imported: Make sure that you've imported the module/package correctly and that the import statement is spelled correctly and available in the correct place in your code.

  2. Wrong file path: If you are importing another file as a module, make sure that the file you are trying to require is located in the correct folder and that you are using the correct file path.

  3. Wrong module/package name: Check the spelling of the package name you are trying to import.


Back to top

My links are not working properly. Should I use a relative or an absolute path?

When linking to other pages within your Express app, as a general rule you should use relative paths that start with a forward slash /.

This way you ensure that the links will work correctly both in your development environment and when the app is deployed.

For example, instead of linking to a page with an absolute path like this:

<a href="http://yourdomain.com/contact"> Contact </a>

You should use a relative path starting with a forward slash / like this:

<a href="/contact"> Contact </a>

Back to top

I got the error "Error: listen EADDRINUSE: Address already in use". How do I fix it?

This error means that the port is taken by another process that is still running on that port.

To fix the issue, you need to kill the process using the port and then run the command again. Here's how to do it:


On Mac/Linux

To kill the process running on port 3000, run the following command in the terminal:

sudo kill -9 $(lsof -t -i:3000)   

Important: Replace the above example port 3000 with the port number of the process you are trying to kill.


On Windows

1. Using the Task Manager

To kill the running process on Windows using the Task Manager do the following:

  1. Open the Task Manager by pressing: Ctrl + Shift + Esc
  2. Find the Node process you want to terminate.
  3. Right-click and select End Task

2. Using Command Prompt

To kill the running process on Windows using the Command Prompt do the following:

  1. Open the windows Start menu
  2. Search for CMD in the search bar
  3. In the search results, right-click on Command Prompt and select Run as administrator. This will open the Command Prompt terminal.
  4. In the Command Prompt terminal, run the following command to find the process ID:
netstat -ano|findstr "PID :3000"

If the process happens to be running on another port, simply replace 3000 with the number the port number the process is running on.

This will return the process id (PID). You should then run the following command using the process id (PID) you got in the previous step to terminate the process:

taskkill /PID 12345 /f

Important: Replace the above example PID 12345, with the process id (PID) you got in the previous step.


Back to top

I got the error "Port is already in use". How do I fix it?

This error means that the port is taken by another process that is still running on that port.

To fix the issue, you need to kill the process using the port and then run the command again. Here's how to do it:


On Mac/Linux

To kill the process running on port 3000, run the following command in the terminal:

sudo kill -9 $(lsof -t -i:3000)   

Important: Replace the above example port 3000 with the port number of the process you are trying to kill.


On Windows

1. Using the Task Manager

To kill the running process on Windows using the Task Manager do the following:

  1. Open the Task Manager by pressing: Ctrl + Shift + Esc
  2. Find the Node process you want to terminate.
  3. Right-click and select End Task

2. Using Command Prompt

To kill the running process on Windows using the Command Prompt do the following:

  1. Open the windows Start menu
  2. Search for CMD in the search bar
  3. In the search results, right-click on Command Prompt and select Run as administrator. This will open the Command Prompt terminal.
  4. In the Command Prompt terminal, run the following command to find the process ID:
netstat -ano|findstr "PID :3000"

If the process happens to be running on another port, simply replace 3000 with the number the port number the process is running on.

This will return the process id (PID). You should then run the following command using the process id (PID) you got in the previous step to terminate the process:

taskkill /PID 12345 /f

Important: Replace the above example PID 12345, with the process id (PID) you got in the previous step.


Back to top

I got the error "Refused to apply style ... ('text/html') is not a supported stylesheet MIME type". What should I do?

This error most commonly occurs when the browser attempts to load a resource (i.e., stylesheet) but the server instead returns an HTML page. For example, if there is an issue with the file path and the server is unable to serve the file, it may return a 404 HTML page.

There are a few things you should look at to troubleshoot this:

  1. Try accessing the file directly: To verify that the server is returning an HTML page instead of the requested file, copy the file path and try to access the file directly from a new browser tab.

  2. Check the file path: Make sure that the file path used is correct and that the file actually exists in that location. If there is a typo or error in the file path, the server will not be able to find the file.

  3. Check the static files middleware configuration: Check that your express.static middleware, which serves static files, is correctly configured and that the right folder path and name are specified. If this middleware is not set up correctly, the server will not send the images when requested.


Back to top

I am getting an error: "not defined". How do I fix it?

The "ReferenceError: variable is not defined" error in JavaScript occurs when you try to access a variable or a function that has not been defined yet or is out of scope. To fix the issue, check that you have defined the variable or function that you are trying to use and double-check the spelling to make sure you are using the correct name. In case the variable or a function is defined in another file, make sure that the file has been imported or loaded correctly.


Back to top

I am unable to push changes to the repository. What should I do?

There are a couple of possible reasons why you may be unable to push changes to a Git repository:

  1. You have not committed your changes: Before you can push your changes to the repository, you need to commit them using the git commit command. Make sure you have committed your changes and try pushing again. To do this, run the following terminal commands from the project folder:
git add .
git commit -m "Your commit message"
git push
  1. You do not have permission to push to the repository: If you have cloned the repository directly from the main Ironhack repository without making a Fork first, you do not have write access to the repository. To check which remote repository you have cloned, run the following terminal command from the project folder:
```bash
git remote -v
```

If the link shown is the same as the main Ironhack repository, you will need to fork the repository to your GitHub account first, and then clone your fork to your local machine to be able to push the changes.

Note: You may want to make a copy of the code you have locally, to avoid losing it in the process.


Back to top

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages