I covered setting up a simple HTTP server using Node.js previously, but that was using the package “http-server” for serving files.
Today I hit the point of needing to write server-side code, so my approach had to change.
Follow these steps to get up and running asap:
- Install Node.js if you haven’t already
- Open your shell of choice (Terminal, Bash, Command Prompt, etc.)
- “cd” to your Project folder
- If you don’t have a “package.json” file, run “npm init” and mash Enter
- Run “npm install express –save” (dash dash save, sorry for WordPress formatting)
- Copy and paste the code below into a new file “server.js”
- Run “node server.js”
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Read these comments first. | |
// Instructions for installing express here: https://expressjs.com/en/starter/installing.html | |
// cd into project directory | |
// run "npm init" | |
// mash enter until it's finished | |
// run "npm install express –save" | |
const express = require("express"); | |
var host = "127.0.0.1"; | |
var port = 8080; | |
var app = express(); | |
app.use('/', express.static(__dirname + '/')); | |
app.listen(port, host); | |
console.log('Running server at http://localhost:' + port + '/'); |