Created
June 8, 2024 13:44
-
-
Save MRezaSafari/a464f20dd2bd061ba4c9dd887c53b2d3 to your computer and use it in GitHub Desktop.
simple http server
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
const express = require("express"); | |
const bodyParser = require("body-parser"); | |
const app = express(); | |
const port = 3000; | |
app.use(bodyParser()); | |
const USER_EMAIL = "[email protected]"; | |
const USER_PASSWORD = "123"; | |
const PRODUCTS = [ | |
{ | |
id: 1, | |
title: "Product 1", | |
price: 35 | |
}, | |
{ | |
id: 2, | |
title: "Product 2", | |
price: 45 | |
} | |
]; | |
app.get("/products", (req, res) => { | |
res.status(200).json(PRODUCTS); | |
}); | |
app.get("/products/:id", (req, res) => { | |
const { id } = req.params; | |
console.log(id) | |
const product = PRODUCTS.find((product) => | |
product.id === +id); | |
res.status(200).json({data: product}); | |
}); | |
app.post("/login", (req, res) => { | |
const { email, password } = req.body; | |
if (email === USER_EMAIL && password === USER_PASSWORD) { | |
res.status(200).json({ | |
message: "Login successful", | |
status: 200 | |
}); | |
} else { | |
res.status(401).json({ | |
message: "Invalid email or password", | |
status: 401 | |
}); | |
} | |
}); | |
app.listen(port, () => { | |
console.log(`Server is running on port ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment