在uni-app中使用H5跨域请求需要进行以下配置:

  1. 在uni-app的manifest.json文件中,找到'h5'节点,添加'devServer'节点,如下所示:
"h5": {
    "devServer": {
        "proxy": {
            "/api": {
                "target": "http://localhost:8080",
                "changeOrigin": true,
                "secure": false,
                "pathRewrite": {
                    "^/api": ""
                }
            }
        }
    }
}
  1. 在上述代码中,'proxy'节点用于配置代理,将请求发送到目标服务器;'changeOrigin'节点用于修改请求头中的'Origin'字段,以便目标服务器识别该请求是从哪个域名发出的;'secure'节点用于设置是否使用安全协议;'pathRewrite'节点用于重写请求路径,将'/api'路径重写为空,以便目标服务器识别请求。

  2. 在代码中发送请求时,需要将请求路径以'/api'开头,如下所示:

uni.request({
    url: '/api/login',
    method: 'POST',
    data: {
        username: 'admin',
        password: '123456'
    },
    success: res => {
        console.log(res.data)
    }
})

通过以上步骤配置后,即可在uni-app中使用H5跨域请求。

uni-app H5跨域配置详解 - 轻松解决跨域问题

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

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