uni-app请求接口跨域
uni-app 采用的是基于 Vue.js 的框架,因此可以借助 Vue.js 的相关插件来解决跨域问题。
一、使用 Vue.js 的 cors 插件
Vue.js 的 cors 插件是一个解决跨域问题的插件,可以实现在 uni-app 中调用接口时跨域访问。使用这个插件需要先安装:
npm install cors
然后在 main.js 中引入:
import cors from 'cors'
Vue.use(cors)
二、使用 uni-app 的 proxyTable 配置
uni-app 也提供了一种跨域解决方案,那就是使用 proxyTable 配置。在根目录下的 uni-app.json 文件中添加以下配置:
{
"networkTimeout": {
"request": 60000,
"downloadFile": 60000
},
"app-plus": {
"useUniConfig": true,
"nvue": {
"support": true,
"resourceCompression": true,
"compiler": {
"presets": [
"es2015"
],
"plugins": [
"transform-remove-strict-mode"
]
}
},
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "uni-app",
"navigationBarTextStyle": "black"
},
"tabBar": {
"color": "#7A7E83",
"selectedColor": "#3cc51f",
"borderStyle": "black",
"backgroundColor": "#ffffff",
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "static/tabbar/home.png",
"selectedIconPath": "static/tabbar/home-active.png"
},
{
"pagePath": "pages/logs/logs",
"text": "日志",
"iconPath": "static/tabbar/logs.png",
"selectedIconPath": "static/tabbar/logs-active.png"
}
]
},
"networkTimeout": {
"request": 10000,
"connectSocket": 10000,
"uploadFile": 10000,
"downloadFile": 10000
},
"debug": true,
"pages": [
"pages/index/index",
"pages/logs/logs"
]
},
"mp-weixin": {
"appid": "wx0f2b2dce6a35a1bb",
"miniprogramType": "normal"
},
"proxyTable": {
"/api": {
"target": "http://localhost:3000",
"pathRewrite": {
"^/api": "/api"
},
"changeOrigin": true,
"secure": false
}
}
}
以上的配置表示,当发送请求的 URL 以 /api 开头时,会将请求代理到 http://localhost:3000,这样就实现了跨域请求。需要注意的是,这个配置只适用于开发环境,生产环境需要在后端服务器上配置跨域
原文地址: https://www.cveoy.top/t/topic/cjpE 著作权归作者所有。请勿转载和采集!