[英]blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response
I'm trying to create a simple frontend using Typescript and a backend server with Flask and send requests via axios
, as I have been using.我正在尝试使用 Typescript 创建一个简单的前端,并使用 Flask 创建一个后端服务器,并通过
axios
发送请求,正如我一直在使用的那样。 Somehow I am getting this strange error in the browser console:不知何故,我在浏览器控制台中收到了这个奇怪的错误:
Access to XMLHttpRequest at 'http://localhost:5000/api/test' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
POST http://localhost:5000/api/test net::ERR_FAILED
It says my header has some field that is illegal due to CORS setup.它说我的标题有一些由于 CORS 设置而非法的字段。 But the thing is:
但问题是:
in app/__init__.py
:在
app/__init__.py
:
from flask import Flask, render_template, jsonify
from flask_cors import CORS
from random import *
import requests
def create_app(Config):
app = Flask(__name__)
CORS(app, support_credentials=True, resources={r"/*": {"origins": "*"}})
app.config.from_object(Config)
app.static_folder = app.config["STATIC_FOLDER"]
app.template_folder = app.config["TEMPLATE_FOLDER"]
with app.app_context():
from app.apis.routers import apis
app.register_blueprint(apis)
return app
in app/apis/routers.py
:在
app/apis/routers.py
:
@apis.after_request
def creds(response):
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response
@apis.route('/api/test', methods=["POST"])
@cross_origin(supports_credentials=True)
def test():
data = request.get_json()
print(data)
response = {
"orderTime": "123-456-789",
"eta": 123
}
return jsonify(response)
{withCredentials: true}
initially.{withCredentials: true}
。 After seeing this error, I removed the header and the request I am sending does NOT have headers AT ALL, but it is still yelling at me that something in the headers is wrong: in customer.tsx
:在
customer.tsx
:
import React, {useState} from 'react';
import { useParams } from "react-router-dom";
import axios from 'axios';
import Button from '@mui/material/Button';
interface ParamTypes {
username: string,
order_id: string
}
interface headerTypes {
'Content-Type': string,
'Access-Control-Allow-Origin': string,
}
// interface Props {
// }
function CustomerContent() {
// constructor(props: Props) {
// super(props);
// }
let {username, order_id} = useParams<ParamTypes>();
console.log(username);
console.log("hi");
const [orderTime, setOrderTime] = useState(0);
const [ETA, setETA] = useState(0);
function buttonHandler() {
let payload = {
username: username,
order_id: order_id,
};
axios.request<ParamTypes, string>({
method: 'post',
url: 'http://localhost:5000/api/test',
data: payload,
})
.then(res => {
console.log(res)
})
setOrderTime(prev => prev + 1);
setETA(prev => prev + 1);
}
return (
<div>
<h1>Hello {username}, this page is for your order with ID: {order_id}</h1>
<p>order placed at: { orderTime } </p>
<p>ETA: { ETA }</p>
<Button variant="contained"
onClick={() => buttonHandler()}>Click to Update Order Status</Button>
</div>
)
}
export default function customer() {
return <CustomerContent />;
}
What is wrong with my code ???我的代码有什么问题???
As it turns out, it only takes a simple setup in the config on the backend side as per How to enable CORS in flask事实证明,根据如何在flask中启用CORS,只需要在后端的配置中进行简单的设置
Thanks @mplungjan for your help!感谢@mplungjan 的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.