To understand how to use the Express.js library to create a back-end file server.
In this lab we will be creating a server that serves any static files, such as HTML, CSS, or JavaScript.
In this lab, you will create a simple file server using Express.js, use that server to access files on a web host, and then limit the files which are served to only those within a specific folder.
- Create a folder
static
which will hold the following: - Create a new file named
index.html
. Inside, use your Emmet abbreviation to create the HTML boiler plate. Have this HTML file display a greeting to the user. - Start the server by running
server.js
usingnode
. - Visit your running server at
http://localhost:5000
with a web browser.
- Did you get this error?
Cannot GET /
- In your server, you will need to set up an index route.
- In the index route's callback function, rather than the
send
method onresponse
, you will need to usesendFile
-
sendFile
takes a directory path as its argument. - You can utilize a node script
__dirname
that will return the path of the folder where the server currently resides.
response.sendFile(__dirname + "/example.html")
- Create a directory named
public
within your project directory. - Move the
index.html
into thepublic
directory. - Update the
server.js
file to limit visitor access to thepublic
directory. You will set up theuse
method onapp
.
app.use(express.static('public'))
- Create at least two more HTML files within the
public
directory. - Create links on the
index
page so that users can navigate to the new pages. - Set up GET routes in your
server.js
and send your new HTML files as response.
In this lab, you practiced creating an Express back-end server that can send arbitrary files from the server to a browser client. You created a default page for the server to send, as index.html
, and also created additional files that can be visited from the index.html
or directly.
Your software should:
- Send different HTML files dependent upon the route in the URL.
- Add a
start
script to thepackage.json
file to make it easier to start your server. In thepackage.json
of your project, navigate to the"scripts:"
object. Create a new key"start"
, and have the value be"node server.js"
. Test your new script withnpm start
! - How could you use
request.params
to dynamically send different files dependent on the value of the param?