vue测试环境跨域问题-配置代理

问题

我们遇到请求后台接口遇到Access-Control-Allow-Origin 时,那说明跨域了,
开发中遇到请求后台接口跨域问题时,可以尝试使用代理方法,需要配置前端代码.

vue版

1.在vue.config.js中设置如下代码片段

devServer: {
    
    
    hot: true,//热更新
    port: 1234,//访问项目时的端口号
    open: true,//编译自动打开浏览器
    secure:false,//若target是https,并且secure是true,就会停止访问
    proxy: {
    
    
      '/api': {
    
    
        target: "http://www.xxx.com",
        ws: true,
        changeOrigin: true,
        pathRewrite: {
    
    
          '^/api': "",
        },
      },
    },
  },

2.注意在使用时url地址需要写成这样,不要带域名,

request({
    
    
    url: '/api/login', //如果proxy下配置的是'api' url要写成'api/login'否则匹配不到
    method: 'post',
    data,
  })

uni-app版

1.在manifest.json文件 源码视图下

"h5": {
    
    
		"devServer": {
    
    
		    "hot": true,
		    "port": 5173,
		    "proxy": {
    
    
		      "/api": {
    
    
		        "target": "http://www.xxx.com",
		        "ws": true,
		        "changeOrigin": true,
		        "pathRewrite": {
    
    
		          "^/api" : ""
		        }
		      }
		    }
		  }
	},

2.注意在使用时url地址注意不要带域名.

猜你喜欢

转载自blog.csdn.net/wepe12/article/details/128632982