Access to XMLHttpRequest Cros 跨域报错的,参数导致问题
0、前言
需求:实现python封装将本地图片存储至minio中的POST接口和获取图片下载外链的get接口,实现前端调用实现图片上传和下载
1、后端接口
# 上传图片接口
@app.route("/upload_image", methods=["POST"])
def upload_image():
data = request.json
bucket_name = data.get("bucket_name")
directory_path = data.get("directory_path")
image_path = data.get("image_path")
if not all([bucket_name, directory_path, image_path]):
return jsonify({"status": "error", "message": "缺少必要的参数"})
result = bucket.upload_image(bucket_name, directory_path, image_path)
return jsonify(result)
# 获取图片外链接口
@app.route("/get_image_url", methods=["GET"])
def get_image_url():
bucket_name = request.args.get("bucket_name")
image_path = request.args.get("image_path")
if not all([bucket_name, image_path]):
return jsonify({"status": "error", "message": "缺少必要的参数"})
result = bucket.get_image_url(bucket_name, image_path)
return jsonify(result)
2、前端接口封装
import http from "./axios";
// 上传图片信息
export function uploadImage(data: any) {
return http({
url: "/upload_image",
method: "post",
data,
});
}
export const uploadData = {
bucket_name: "cloud",
directory_path: "detected",
image_path: "url", // 图片本地存储路径
}
// 获取图片下载外链
export function getImageUrl(bucket_name: string, image_path: string) {
return http({
url: "/get_image_url",
method: "get",
params: {
bucket_name,
image_path, // 图片minio存储路径
},
});
}
3、参数输入,调用前端接口
这里以获取外链为例
<script setup>
import { getImageUrl } from '@/api/detected/detectedAPI'
import { ElMessage } from 'element-plus';
const handleFileChange = (event) => {
const fileName = event.target.files[0];
getImageUrl(fileName,'cloud/detected/'+fileName).then(res => {
console.log(res)
ElMessage.success('获取外链成功')
}).catch(err => {
console.log(err)
})
};
</script>
<template>
<div>
<input type="file" @change="handleFileChange" />
</div>
</template>
4、出现报错
5、debug
进行排错:首先,后端做好了跨域并使用apifox测试,可成功获取下载外链,排除后端书写接口问题,接下来检查前端代码,是否存在调用时机问题,使用console.log获取发现时机按照预期,最后即检查传入参数时候是否正确(这里的检查框较小其中的报错刚好隐藏了参数导致排错较慢),打印可见一个时object一个是目标参数,同时将检查框拉大也可见
至此解决所谓跨域报错。