Get parameter and Post body, enable CORS in Flask (Python) and Express (Node.js)

Below, we will look at 6 items. I am sending from an HTML file. Both sending and receiving are done locally. If you try it on the server, please read the domain as appropriate.

  1. Get Flask Get Parameter
  2. Get Flask Post Body
  3. Enable Flask Cors
  4. Get Express Get Parameter
  5. Get Express Post Body
  6. Enable Express Cors

Please note that all Content-Types are sent and received in application / json. If you use other styles, please read as appropriate ~.

HTML (sender)

View it in your browser and run

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" name="id" id="body">
    <button id="click">Send</button>
    <script>
        document.querySelector("#click").addEventListener("click",function(){
            let data = document.querySelector("#body").value;            
            //Get
            const params = new URLSearchParams();
            params.set("id",data);
            fetch("http://localhost:5000/get" + "?" + params.toString())
                .then((res)=>{
                    if(!res.ok){
                        throw new Error();
                    }
                    return res.json();
                })
                .then((res)=>{
                    console.log(res)
                })
                .catch((res)=>{
                    console.log(`Error Response : ${res}`);
                })

            //Post
            const body = {
                id: data
            };
            fetch("http://localhost:5000/post",{
                method: "POST",
                headers: {
                    'Content-Type' : "application/json"
                },
                body: JSON.stringify(body)
            })
                .then((res)=>{
                    if(!res.ok){
                        throw new Error();
                    }
                    return res.json();
                })
                .then((res)=>{
                    console.log(res)
                })
                .catch((res)=>{
                    console.log(`Error Response : ${res}`);
                })
        })
    </script>
</body>
</html>

When using Flask (receiver)

# -*- encoding:utf-8 -*-
import os
import sys
import json
from flask import Flask, render_template, request
from logging import getLogger, StreamHandler, DEBUG, INFO, WARNING, ERROR, CRITICAL

app = Flask(__name__)

#Log settings
logger = getLogger(__name__)
handler = StreamHandler()
handler.setLevel(DEBUG)
logger.setLevel(os.getenv("LogLevel", DEBUG))
logger.addHandler(handler)
logger.propagate = False

#Enable CORS
@app.after_request
def after_request(response):
    logger.debug(f"\033[33m{sys._getframe().f_code.co_name} function called\033[0m")
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    return response

#Get Parameter Get
@app.route('/get')
def get():
    #Argument check
    if "id" not in request.args:
        logger.warning("id Parameter is not send")
        return json.dumps({"message": "send message"})

    ID = request.args.get('id')
    logger.info(f"ID = {ID}")

    return json.dumps({"Get message": ID})

#Get Post body
@app.route('/post',methods=["POST"])
def post():
    logger.info(f"request.data={request.data}")
    data = request.get_json()
    logger.debug(f"data = {data}")
    logger.debug(f"type(data) = {type(data)}")

    #application/If you receive it in json format, you can also receive it as follows
    logger.debug(f"request.json = {request.json}")
    logger.debug(f"type(request.json) = {type(request.json)}")

    #Argument check
    if "id" not in request.json:
        logger.warning("id Parameter is not send")
        return json.dumps({"message": "send message"})

    ID = request.json["id"]
    logger.info(f"ID = {ID}")

    return json.dumps({"Post message": ID})

if __name__ == "__main__":
    app.run(host='0.0.0.0',port=5000)

When using Express (receiver)

*** If the version of Express is 4.16 or later, body-parser is not required and can be implemented only with express ***

const express = require('express');
const app = express()
/**
 * Express 4.After 16 body-express implemented based on parser.json()
 *You can get the POST body with.
 *Therefore, req as follows.There is no need to do a body.
 * 
 * const bodyParser = require('body-parser');
 * app.use(bodyParser.urlencoded({ extended: false }));
 */
app.use(express.json()); //Content-Type is application/Need this if sent as json
app.use(express.urlencoded({ extended: true }));

 //Enable CORS
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

//Get Parameter Get
app.get('/get', (req, res) => {
  let response = "";
  console.log(req.query);
  console.log(typeof req.query);
  if(req.query.hasOwnProperty("id")){
    response = req.query.id
  }
  res.json({"Get Parameter" : response});
})

//Get Post body
app.post('/post', (req, res) => {
  let response = "";
  console.log(req.body);
  console.log(typeof req.body);
  if(req.body.hasOwnProperty("id")){
    response = req.body.id
  }
  res.json({"Post Body" : response});
})

//Write a callback function to be performed immediately after the start of standby in the second argument of listen.
app.listen(5000)

Recommended Posts

Get parameter and Post body, enable CORS in Flask (Python) and Express (Node.js)
Get, post communication memo in Python
POST variously with Python and receive with Flask
(For myself) Flask_3 (form, POST and GET)
POST JSON in Python and receive it in PHP
Get Gmail subject and body with Python and Gmail API
Get your current location and user agent in Python
Get stock prices and create candlestick charts in Python
GET / POST communication by Flask (also about CORS support)
Get date in Python
Get the MIME type in Python and determine the file format
Get the current date and time in Python, considering the time difference
Get YouTube Comments in Python
Get last month in python
Install Python and Flask (Windows 10)
Use parameter store in Python
Get Terminal size in Python
Explicitly get EOF in python
Stack and Queue in Python
Unittest and CI in Python
[python] Get quotient and remainder
Get Evernote notes in Python
Transfer parameter values in Python
Post to Slack in Python
Get Japanese synonyms in Python
[ROS2] How to describe remap and parameter in python format launch
I compared Node.js and Python in creating thumbnails using AWS Lambda
Get the title and delivery date of Yahoo! News in Python