第一次上手uniapp做项目, 碰到的坑-前端ajax请求 报跨域问题.
1. 服务器真实没有处理解决跨域问题
配置 uni-app 中 manifest.json->h5->devServer
"h5": {
"devServer": {
"port": 8080,//端口
"disableHostCheck": true,
"proxy": {
"/api": {
"target": "http://www.xxxxx.net",//目标接口域名
"changeOrigin": true,//是跨域
"secure": false,//设置支持https协议的代理
}
}
}
}
其中参数解析详见: https://www.jb51.net/article/180961.htm
更多其他解决方式详见: https://ask.dcloud.net.cn/article/35267
2. 服务器端已处理解决跨域问题,但访问仍然跨域错误
Access to XMLHttpRequest at 'http://xxxxx.com/api/public/getLiveClass' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
浏览器console调试器(在360极速浏览器环境下)报错如下:
仅在360极速浏览器下的network中出错请求 headers 如下:
经过几个小时的翻查资料,终于发现 uni.request的header参数中,设置content-type 为 'application/x-www-form-urlencoded' 能解决 上述跨域问题.
header: {
'content-type': 'application/x-www-form-urlencoded',
}
使用uview封装的http请求工具时,也报上述问题,解决方法如下:
找到http.interceptor.js文件,修改成方框指示的样子即可:
修改原因: uview的http请求工具中 , header中的content-type默认设置为'application/json;charset=UTF-8' , 服务器端不识别 , 所以请求变成了'options'. 在上面图片文件的截图指示位置 , 重新设置content-type为'application/x-www-form-urlencoded' , 就好使了.
若还是跨域报错, 则把http.interceptor.js文件 'config.header.token = 'xxxxxx'' 给注释掉.