首页 > 其他分享 >记录一次uniapp 开发环境访问本机接口 报跨域的问题

记录一次uniapp 开发环境访问本机接口 报跨域的问题

时间:2022-11-24 15:13:54浏览次数:45  
标签:uniapp http 跨域 接口 h5 H5 localhost

报错信息:

Access to XMLHttpRequest at 'http://localhost:9999/test/ping' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • 查看服务器请求日志,发现服务器有正常返回
  • 将接口地址换成另一个同样配置的有域名的地址,访问能正常拿到结果

仿佛记得以前是可以这样访问的,难道是太久没做这块已经忘了?暂时只能参考vue的推荐做法,在manifest中配置devServer走node的服务代理:

"devServer": {
			"proxy": {
				"/dpc": {
					"target": "http://127.0.0.1:9999", //域名
					"changeOrigin": true,
					"secure": false,
					"pathRewrite": {
						"^/dpc": ""
					}
				}
			},
			"https": false
		}

线下环境和线上环境区分开配置(package.json):

"uni-app": {
		"scripts": {
			"h5-dev": {
				"title": "H5线下",
				"browser": "chrome",
				"env": {
					"UNI_PLATFORM": "h5",
					"API_HOST": "/dpc",
					"VERSION": "1.0.0"
				},
				"define": {
					"H5-DEV": true
				}
			},
			"h5-prod": {
				"title": "H5线上",
				"browser": "chrome",
				"env": {
					"UNI_PLATFORM": "h5",
					"API_HOST": "https://线上接口地址,
					"VERSION": "1.0.0"
				},
				"define": {
					"H5-PROD": true
				}
			}
		}
	}

如果有其他更好方法,请不吝赐教!

标签:uniapp,http,跨域,接口,h5,H5,localhost
From: https://www.cnblogs.com/Denny_Yang/p/16921879.html

相关文章