Creating a simple server
Now that we can render components to HTML strings, it would serve us better to have a way to respond to HTTP requests with HTML responses.
Fortunately, Node.js also includes a neat little HTTP server library. We can use the following code, in the server.js
file, to respond to HTTP requests:
var http = require("http"); var server = http.createServer( function (request, response) { response.writeHead(200, { "Content-Type": "text/html" }); response.end( require("./hello-world") ); } ); server.listen(3000, "127.0.0.1");
To use the HTTP server library, we need to require/import it. We create a new server, and in the callback parameter, respond to individual HTTP requests.
For each request, we set a content type and respond with the HTML value of our hello-world.js
file. The server listens on port 3000
, which means you'll need to open http://127.0.0.1:3000
to see this message.
Before we can do that, we also...