Dev
Python
Flask service
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def webhook():
try:
# Access data sended by POST
data = request.json
except Exception as e:
# Exception catched
return '', 200
if __name__ == '__main__':
# Run app
app.run(host='0.0.0.0', port=5001)JS
Node server
const express = require("express");
const app = express();
const PORT = 8000;
app.get("/", async (req, res) => {
//...
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});req(request): Represents the HTTP request object, containing data such as headers, query parameters, and request body.res(response): Represents the HTTP response object, used to send data back to the client.
1. Expecting GET Data (Query Parameters & URL Params)
a) Query Parameters (req.query)
Query parameters are sent in the URL after a
?and separated by&.Example URL:
/search?keyword=express&limit=10Access query parameters using
req.query:app.get("/search", (req, res) => { const keyword = req.query.keyword; // "express" const limit = req.query.limit; // "10" res.send(`Search for: ${keyword}, Limit: ${limit}`); });Use case: Searching, filtering, pagination, etc.
b) Route Parameters (req.params)
Route parameters are part of the URL path (e.g.,
/user/:id).Example URL:
/user/123Access route parameters using
req.params:app.get("/user/:id", (req, res) => { const userId = req.params.id; // "123" res.send(`User ID: ${userId}`); });Use case: Fetching details of a specific item or user.
2. Expecting POST Data (Body Data)
For POST, PUT, PATCH requests, the data is usually sent in the request body.
a) JSON Data (req.body)
Ensure Express can parse JSON by using the
express.json()middleware.Example request body (JSON):
{ "username": "john_doe", "password": "secure123" }Express route to handle it:
const express = require("express"); const app = express(); app.use(express.json()); // Middleware to parse JSON app.post("/login", (req, res) => { const { username, password } = req.body; res.send(`Logging in user: ${username}`); }); app.listen(3000, () => console.log("Server running on port 3000"));Use case: Login, submitting forms, creating records.
b) Form Data (application/x-www-form-urlencoded)
If the form sends data as
application/x-www-form-urlencoded(default for HTML forms), use:app.use(express.urlencoded({ extended: true }));Example HTML form:
<form action="/submit" method="post"> <input type="text" name="name" /> <input type="email" name="email" /> <button type="submit">Submit</button> </form>Express route:
app.post("/submit", (req, res) => { const name = req.body.name; const email = req.body.email; res.send(`Received: ${name}, ${email}`); });
Last updated