Uniapp 跨域问题解决方案 | 如何解决跨域请求
在 Uniapp 中,要解决跨域问题,需要在 uni-app 工程的根目录下的 main.js 文件中加上以下代码:
// main.js
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
App.mpType = 'app'
// 配置请求根路径
Vue.prototype.$baseUrl = 'http://localhost:8080'
const app = new Vue({
store,
...App
})
app.$mount()
// 解决跨域问题
Vue.prototype.$http = function (url, method, data, success, fail) {
uni.request({
url: this.$baseUrl + url,
method: method,
data: data,
success: function (res) {
success(res)
},
fail: function (err) {
fail(err)
}
})
}
其中,$baseUrl 是请求根路径,可以根据实际情况进行修改。$http 是用来发送请求的函数,通过 uni.request 方法来发送请求,其中的 url 需要加上 $baseUrl,以解决跨域问题。
在需要发送请求的地方,可以直接调用 this.$http 方法来发送请求:
this.$http('/login', 'POST', {
username: 'admin',
password: '123456'
}, function (res) {
console.log(res)
}, function (err) {
console.log(err)
})
这样就可以在 Uniapp 中解决跨域问题了。
原文地址: https://www.cveoy.top/t/topic/oAOT 著作权归作者所有。请勿转载和采集!