Vue test environment cross-domain problem - configure proxy

question

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

vue version

1. Set the following code snippet in 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. Note that the url address needs to be written like this when using it, without a domain name.

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

uni-app version

1. In the manifest.json file source code view

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

2. Be careful not to include a domain name in the url address when using it.

Guess you like

Origin blog.csdn.net/wepe12/article/details/128632982