[Memorandum] Hit API using Javascript asynchronous processing
JavaScript fetch to hit the API using fetch()
What is the Fetch function?
The Fetch API is a JavaScript interface for accessing elements that manipulate the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that allows you to fetch resources asynchronously across the network in a simple and logical manner. Traditionally, such functionality has been achieved using XMLHttpRequest. Fetching is a better alternative to it and can easily be used from other technologies such as service workers. Fetching is also a place to collectively define concepts related to HTTP such as CORS and extensions to HTTP. From Mozilla About details fetch
Sample of hitting API
Code:
function getapi() {
const url = API url; #apiのurl
if (!word) {
return "Loading...";
}
return fetch(url)
.then((res) => res.json())
.then((data) => (data != null ? data : "Loading..."));
}
async function useapi() {
let text = await getapi();
htmlelemnt = text;
}
Cross Origin Resource Sharing (CORS)
Error:
Access to XMLHttpRequest at 'http://localhost:8081' from origin 'http://localhost:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Error...? I'm sure many of you have seen CORS policy before, or have thought it's the one that sometimes appears when you hit the API.
First of all, what is "Same-Origin Policy"?
CORS is a policy that loosens the restrictions set by the Same-Origin Policy.
Therefore, in order to understand CORS, it is necessary to first understand what the "Same-Origin Policy" is.
Same Origin Policy
Simply put, the "same origin policy" means that "JavaScript can be freely manipulated only in the same place as the html from which the JavaScript is loaded.
It is a security mechanism for handling information and is called an "identical origin policy.
The combination of protocol, host, and port is called "origin," and if they are the same, they are considered to be the same and treated as information within the same scope of protection.
Because of this restriction, it is not possible to download JavaScript from one server and access a completely different server from that script to obtain information from there. Security is increased by preventing unauthorized logins, unauthorized payments, etc.
Therefore, when making CORS requests that are not originally allowed, it is necessary to allow them on the server side.
CORS implementation in Fast API
Code:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:8080"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def main():
return {"message": "OK!"}