首先需明确uni.request不支持使用 jsonp 方案去解决跨域问题。
最直接的解决办法就是:在uni-app 的项目中找到manifest.json这个配置文件,在该配置文件中配置跨域代理(代理服务器)
解决方案如下:
选择源码视图对manifest.json配置文件进行编辑:增加这块内容
"h5": {
"devServer": {
"proxy": {//配置代理服务器来解决跨域问题,uniapp不适用CORS方案和设置JSONP方案
"/api/": { //映射域名
"target": "http://localhost:3000",
"pathRewrite": {
"^/api": ""
}
}
}
}
}
完整视图代码:
{
"name": "wx-MiniPro",
"appid": "__UNI__06A0CD9",
"description": "",
"versionName": "1.0.0",
"versionCode": "100",
"transformPx": false,
/* 5+App特有相关 */
"app-plus": {
"usingComponents": true,
"nvueStyleCompiler": "uni-app",
"compilerVersion": 3,
"splashscreen": {
"alwaysShowBeforeRender": true,
"waiting": true,
"autoclose": true,
"delay": 0
},
/* 模块配置 */
"modules": {},
/* 应用发布信息 */
"distribute": {
/* android打包配置 */
"android": {
"permissions": [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
/* ios打包配置 */
"ios": {},
/* SDK配置 */
"sdkConfigs": {}
}
},
/* 快应用特有相关 */
"quickapp": {},
/* 小程序特有相关 */
"mp-weixin": {
"appid": "",
"setting": {
"urlCheck": false
},
"usingComponents": true
},
"mp-alipay": {
"usingComponents": true
},
"mp-baidu": {
"usingComponents": true
},
"mp-toutiao": {
"usingComponents": true
},
"uniStatistics": {
"enable": false
},
"h5": {
"devServer": {
"proxy": {//配置代理服务器来解决跨域问题,uniapp不适用CORS方案和设置JSONP方案
"/api/": {//映射域名
"target": "http://localhost:3000",
"pathRewrite": {
"^/api": ""
}
}
}
}
}
}
重启项目,当前端再次发起uni.request()接口请求时,不再受浏览器同源策略CORS的影响,也不再需要配置请求头:Access-Control-Allow-Origin
uni.request({
url: '/api/retroaction',
method: 'POST',
data: {},
success: res => {console.log(JSON.stringify(res))},
fail: () => {},
complete: () => {}
});