vue设置代理解决跨域

        跨域的问题在前后端分离的项目中经常会遇到,设置代理解决跨域问题。

方法一

        在vue项目中 vue.config.js(与package.json是同一级的) 文件中配置

module.exports = defineConfig({
  devServer: {
    proxy: 'http://47.100.232.228:3000'
  }
})

        只能配置一个后端地址。

方法二

        如果一个项目要请求多个地址,在 vue.config.js 文件中配置

module.exports = defineConfig({
  devServer: {
    proxy: {
      '/api': {
        target: 'http://47.100.232.228:3000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      '/api1': {
        target: 'http://47.100.232.228:5000',
        changeOrigin: true,
        pathRewrite: {
          '^/api1': ''
        }
      }
    }
  }
})

        target是目标地址,pathRewrite是重写地址。

        在请求后端接口时,后端接口的路径也需要改。

        例如原来请求接口路径是:http://47.100.232.228:3000/login

        设置代理之后需要加前缀,为:http://localhost:8080/api/login

本机尽量使用  localhost  ,用  127.0.0.1  有时候会访问不到。

猜你喜欢

转载自blog.csdn.net/h360583690/article/details/129677224