React+Redux调用Django API遭遇CORS跨域问题求助
解决Django + React/Redux中的CORS问题
问题场景
前端应用运行在http://localhost:3000,后端Django API部署在http://localhost:8000,调用/api/list-accounts接口时触发CORS错误,但其他API请求均正常。
浏览器控制台报错
Access to XMLHttpRequest at 'http://localhost:8000/api/list-accounts' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
技术实现代码
Redux异步Action(获取账户数据)
export const fetchAccounts = () => { return async (dispatch: Dispatch) => { try { dispatch(fetchAccountsRequest()); const response = await axios.get(`${API_BASE_URL}/list-accounts`, { withCredentials: true, }); const accounts = response.data; dispatch(fetchAccountsSuccess(accounts)); } catch (error) { dispatch(fetchAccountsFailure(error)); } }; }; const fetchAccountsRequest = () => ({ type: ActionTypes.FETCH_ACCOUNTS_REQUEST, }); const fetchAccountsSuccess = (accounts: Account[]) => ({ type: ActionTypes.FETCH_ACCOUNTS_SUCCESS, payload: accounts, }); const fetchAccountsFailure = (error: any) => ({ type: ActionTypes.FETCH_ACCOUNTS_FAILURE, payload: error, });
React组件(CardWithAccounts)
export function CardWithAccounts() { const dispatch = useAppDispatch(); const accounts = useAppSelector((state:RootState) => state.accounts.accounts) const loading = useAppSelector((state: RootState)=> state.accounts.loading) useEffect(() => { dispatch(fetchAccounts()) }, [dispatch]) if (loading) { return <div>Loading...</div> } return ( <div></div>) }
已尝试的Django CORS配置
CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_CREDENTIALS = True # 中间件包含 "corsheaders.middleware.CorsMiddleware", ALLOWED_HOSTS = ["127.0.0.1","localhost"]
排查与解决建议
- 调整中间件顺序:确保
CorsMiddleware放在CommonMiddleware之前,是所有请求处理中间件的第一个,示例:MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", # 其他中间件 ] - 验证API端点配置:检查
/api/list-accounts视图是否正确应用CORS规则,若使用Django REST Framework,确认视图继承APIView或全局配置未被局部覆盖;若用了@csrf_exempt,需确保CORS头能正常添加。 - 检查预检请求:用curl或Postman发送
OPTIONS请求到目标接口,查看响应头是否包含Access-Control-Allow-Origin: http://localhost:3000——预检请求失败会直接导致CORS错误。 - 排查响应头覆盖:确认没有其他安全中间件修改/覆盖CORS相关响应头,比如
SecurityMiddleware的某些配置。 - 清除浏览器缓存:旧缓存的响应头可能导致异常,清空缓存后重新测试。
- 检查路由与视图:确认
/api/list-accounts路由配置正确,视图未抛出异常(异常会导致CORS头无法正常添加)。
内容的提问来源于stack exchange,提问作者Enmanuel
相关产品推荐
相关产品推荐

