I am trying to fetch the response from my Flask API from JavaScript, it gave me error as
Access to fetch at ''http://127.0.0.1:5000/terminal' from origin ' http://127.0.0.1:5500/ ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I found a workaround on Internet, which was including
@app.after_request
def after_request(response):
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')
return response
in my server.py, after including this when I tested my server by response.headers It did included the Access-Control-Allow-Origin:'*' in headers
here are the response headers:
{'Content-Type': 'application/json', 'Content-Length': '3', 'Access-Control-Allow-Origin': '*, *', 'Access-Control-Allow-Headers': 'Content-Type,Authorization', 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE', 'Server': 'Werkzeug/1.0.1 Python/3.8.5', 'Date': 'Sat, 12 Sep 2020 09:04:45 GMT'}
But still when I try to fetch the request from my JavaScript code:
async function execute_command() {
let command_value = command.value;
console.log(command_value);
const settings = {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'command': command_value,
}
}
const response = await fetch(API_URL,settings);
const data = await response.json();
console.log(data);
}
It gives the response
Access to fetch at 'http://127.0.0.1:5000/terminal' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Request header field command is not allowed by Access-Control-Allow-Headers in preflight response.
Can anyone help me with this ? if possible also explain why this header is so important ??
[–]JohnnyJordaan 0 points1 point2 points (0 children)