vue和django接口联调

vue访问服务端接口

配置跨域

前端跨域

打开vite.config.js,在和resolve同级的地方添加配置。

proxy代表代理的意思

"/api"是以/api开头的路径走这个配置

target代表目标

changeOrigin: true,是开启跨域请求

rewrite是编辑路径。

(path) => path.replace(/^\/api/, "")是去掉/api

这样一个路径进来就会被处理,如下:

"/api/config" --> "http://localhost:8000/config"

python 复制代码
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:8000",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, "")
      }
    }
  },

后端跨域

配置api

在utils下新建apis.js文件

注意,我们只配置了/api,所以只有/api开头的路径才能走vite.config.js中的跨域配置。

配置好api文件后记得对外暴露

python 复制代码
// 用于访问服务端接口
const apiHost = "/api"


const systemAPIs = {
    sliderListUrl : apiHost + "/system/slider/list", 
}


export{
    systemAPIs
}

访问数据

在app.vue页面中完成访问数据

python 复制代码
const bannerList = ref([])
// 访问接口获取数据

const getBannerList = () => {
  ajax.get(systemAPIs.sliderListUrl).then(res => {
    bannerList.value = res.data.objects
    console.log(bannerList.value)
    console.log(res)
  })
}

// 页面元素加载前调用getBannerList函数
onMounted(() => {
  getBannerList()
})

其它问题

获取数据时我们用了res.data.objects,其中objects是后端传回的key值。

配置api的时候注意一定要和后端的路由完全相同,不能有任何区别,包括结尾的/,路由中有那访问路径中也一定要有。

无参数的get在路由的请求结尾已经要加/,有参数的get不能加/

相关推荐
NiceCloud喜云5 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby5 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing5 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩5 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车5 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
Front思6 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫8 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。9 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星9 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒9 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端