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.
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>
# -*- 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)
*** 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