Vue设置跨域(代理服务)

在平时的项目开发中,经常会用到前后端分离的开发方式,若你使用Vue,那不设置跨域的话会因为同源的限制导致后台数据接口访问不到。今天,博主就来告诉大家如何设置跨域(代理服务)

先假设你的后台数据接口是:http://127.0.0.1:5000/admin/login

这时,如果你直接去访问这个数据接口的话,你100%访问不到。除非你同源,同协议,同域名。

这时候,我们就需要在Vue.config.js中进行配置了:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  devServer: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:5000',
        changeOrigin: true,
        pathRewrite: { '^/api': '' }
      }
    }
  }
})

配置devServe

配置完这些之后,接下来怎么办呢?

回到你要发送请求的地方:

      axios
        .post("/api/admin/register", this.form)
        .then((res) => {
          ...
        })
        .catch((err) => {
          ...
        });

这样在访问此接口时,就不会出现跨域错误了。

posted @ 2022-08-11 22:19  抗争的小青年  阅读(448)  评论(0编辑  收藏  举报