Setting up a server to do both static and dynamic queries
We will need our server to handle both static and dynamic queries. Fortunately,
our very first server was dynamic, and
node already has a module that handles static queries.
- Start off by logging into your server account on
server162.site, using ssh and your Kerberos login.
Find your
port number, and add it to the server
from Wednesday's lecture, miniServer.js.
Try it out!
- Now check out the documentation for the npm module
node-static,
which can be used to add
a static server.
To install the module, use npm, the Node Package Manager,
as follows:
npm node-static.
-
Try out the static server example from the
"synopsis" box in the documentation. We will go
over its meaning in class on Friday.
You'll need to create a /public directory under your server directory.
In order to have some static files to server, you can put
testWHS.html,
testWHS.css, and testWHS.js
into public. Does it work?
-
To make sure you understand the static server code (it's hard, but
you will be expected to know
this kind of stuff
as a full-stack developers), refactor the server code so that
- All the "require" statements are at the top of the file, not in the middle of the code.
- The server is created by a single line
var server = http.createServer(handler);
and the last line of the file is
server.listen("your port number");
as in the miniServer, and the handler function that does all the work has a name.
-
Now that the two servers look similar, let's merge them together, into a file
called SnDserver.js.
The goal is that a browser going to
http://server162.site:{your port number}/testingWHS.html
should still find the Web page, and a browser going to
http://server162.site:{your port number}/query/do anything else
should get the goofy message that miniServer sends.
- Finally, make the server respond with a "404 not found"
page if it gets a url that neither begins
with "query" nor is the name of a static file in the
/public directory. There is some information on how to do this
on the
node-static documentation, in the
section on "serving specific files". Notice that the static file
server object changes its name from "file" to "fileServer" (grrr!!!)
in this section of the documentation.
You'll need to modify the server some more to handle AJAX queries, so
don't hand it in yet.