当前位置: 首页 > article >正文

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一个是目标参数,同时将检查框拉大也可见

至此解决所谓跨域报错。


http://www.kler.cn/a/551796.html

相关文章:

  • 前端知识速记 - CSS篇:可继承属性与不可继承属性
  • STL —— 洛谷字符串(string库)入门题(蓝桥杯题目训练)(一)
  • 如何简单的去使用jconsloe 查看线程 (多线程编程篇1)
  • 【Python】pypinyin-汉字拼音转换工具
  • LSTM细胞状态门控设计详解:数学原理、代码实现与工业级优化方案
  • 【嵌入式Linux应用开发基础】exec()函数族
  • Servlet中HttpServletRequest和HttpServletResponse的常用API
  • 文档生成视频转换工具,让一切皆可制作成视频
  • 【杂谈】加油!!!!
  • 策略模式 Strategy Pattern
  • 认识HTML的标签结构
  • Uboot编译出现:Makefile:40: *** missing separator. Stop.
  • apache artemis安装
  • H3CNE构建中小企业网络(上)面向零基础
  • AIGC(生成式AI)试用 21 -- Python调用deepseek API
  • Linux 文件内容查看
  • Docker 安全基础:权限、用户、隔离机制
  • http状态码503之解决方法(Solution to HTTP Status Code 503)
  • 部署k8s 集群1.26.0(containerd方式)
  • AI 百炼成神:线性回归,预测房价