Skip to content

Instantly share code, notes, and snippets.

@katychuang
Last active October 16, 2024 19:05
Show Gist options
  • Save katychuang/f94b394551e03ec18c8b4e47d3bf4042 to your computer and use it in GitHub Desktop.
Save katychuang/f94b394551e03ec18c8b4e47d3bf4042 to your computer and use it in GitHub Desktop.
minimal example of API using expressjs. Demo: https://youtu.be/0Tj7u-8Iav0
const express = require("express");
const app = express();
const router = express.Router();
app.use(express.json());
const port = 3000;
// Start server
app.listen(port, () => {
console.log("Server running on port %PORT%".replace("%PORT%",port))
});
// Insert here other API endpoints
/*
GET Requests
/
/one
POST Requests
/two
*/
// Root endpoint
app.get("/", (req, res, next) => {
res.send("API end points include /one, /two");
});
// the `/one` endpoint showing hard coded json object
app.get("/one", (req, res, next) => {
res.status(200).json({"name": "one"});
});
// the `/two` endpoint
app.post("/two", (req, res) => {
res.status(200).json(req.body);
});
// Default response for any other request
app.use(function(req, res){
res.status(404);
});
default:
node api.js
install:
npm install express
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment