在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中解决跨域问题了

uniapp跨域问题

原文地址: https://www.cveoy.top/t/topic/g6bi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录