CHAPTER 2Scaffolding the Server
-
Create a file
src/server.ts
:import express from "express"; import cors from "cors"; import morgan from "morgan"; const app = express(); app.use(cors()); app.use(morgan("dev")); app.use(express.json()); app.get("/", async (req, res) => { res.json({ message: "hello!" }); }); const { PORT } = process.env; app.listen(PORT, () => { console.log(`Forum API listening on port ${PORT}`); });
-
Select it as the
"main"
file inpackage.json
:{ // ... "main": "src/server.ts" // ... }
-
Add the
PORT
variable to the.env
file. (We will assume 8888 here.) -
Run the server with
bun run src/server.ts
and check that it works.
-
Change to another terminal (install
httpie
if you don't have it), and run:http GET localhost:8888/
You should get something like:
HTTP/1.1 200 OK Access-Control-Allow-Origin: * Content-Length: 20 Content-Type: application/json; charset=utf-8 Date: Wed, 24 Apr 2024 17:51:01 GMT ETag: W/"14-li7HDh+tAWW33cIYjDrXLcX526M" X-Powered-By: Express { "message": "hello!" }
-
Create
"scripts"
inpackage.json
to launch the server in development and production:{ "scripts": { "dev": "bun --hot src/server.ts", "start": "NODE_ENV=production bun src/server.ts" } }
-
Start the server with
bun run dev
and check that if you changeserver.ts
the server reloads.