uniapp跨域问题

uni-app的跨域问题解决方案

常见解决方案有两种

服务器端解决方案

服务器告诉浏览器:你允许我跨域

具体如何告诉浏览器,请看:

// 告诉浏览器,只允许 http://bb.aaa.com:9000 这个源请求服务器
$response->header('Access-Control-Allow-Origin', 'http://bb.aaa.com:9000');
// 告诉浏览器,请求头里只允许有这些内容
$response->header('Access-Control-Allow-Headers', 'Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, X-File-Type, Cache-Control, Origin');
// 告诉浏览器,只允许暴露'Authorization, authenticated'这两个字段
$response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
// 告诉浏览器,只允许GET, POST, PATCH, PUT, OPTIONS方法跨域请求
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
// 预检
$response->header('Access-Control-Max-Age', 3600);

将以上代码写入中间件:

// /app/Http/Middleware/Cors.php
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;
class Cors {
    
    

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
    
    
        $response = $next($request);
        // 告诉浏览器,只允许 http://bb.aaa.com:9000 这个源请求服务器
        $response->header('Access-Control-Allow-Origin', 'http://bb.aaa.com:9000');
        // 告诉浏览器,请求头里只允许有这些内容
        $response->header('Access-Control-Allow-Headers', 'Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, X-File-Type, Cache-Control, Origin');
        // 告诉浏览器,只允许暴露'Authorization, authenticated'这两个字段
        $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
        // 告诉浏览器,只允许GET, POST, PATCH, PUT, OPTIONS方法跨域请求
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
        // 预检
        $response->header('Access-Control-Max-Age', 3600);
        return $response;
    }

}

在路由上添加跨域中间件,告诉客户端:服务器允许跨域请求

$api->group(['middleware'=>'cors','prefix'=>'doc'], function ($api) {
    
    
    $api->get('userinfo', \App\Http\Controllers\Api\UsersController::class.'@show');
    
})

客户器端解决方案

欺骗浏览器,让浏览器觉得你没有跨域(其实还是跨域了,用的是代理)

manifest.json里添加如下代码:

// manifest.json
"devServer" : {
    
    
    "port" : 9000,
    "disableHostCheck" : true,
    "proxy": {
    
    
        "/api/doc": {
    
    
            "target": "http://www.baidu.com",
            "changeOrigin": true,
            "secure": false
        },
        "/api2": {
    
    
          .....
        }
    },
    
},

参数说明

‘/api/doc’
捕获API的标志,如果API中有这"/api/doc"个字符串,那么就开始匹配代理,
比如API请求"/api/doc/userinfo", 
会被代理到请求 "http://www.baidu.com/api/doc"
即:将匹配到的"/api/doc"替换成"http://www.baidu.com/api/doc"
客户端浏览器最终请求链接表面是:"http://192.168.0.104:9000/api/doc/userinfo",
实际上是被代理成了:"http://www.baidu.com/api/doc/userinfo"去向服务器请求数据
target
代理的API地址,就是需要跨域的API地址。 
地址可以是域名,如:http://www.baidu.com
也可以是IP地址:http://127.0.0.1:9000
如果是域名需要额外添加一个参数changeOrigin: true,否则会代理失败。
pathRewrite
路径重写,也就是说会修改最终请求的API路径。 
比如访问的API路径:/api/doc/userinfo, 
设置pathRewrite: {'^/api' : ''},后,
最终代理访问的路径:"http://www.baidu.com/doc/userinfo", 
将"api"用正则替换成了空字符串,
这个参数的目的是给代理命名后,在访问时把命名删除掉。
changeOrigin
这个参数可以让target参数是域名。
secure
secure: false,不检查安全问题。
设置后,可以接受运行在 HTTPS 上,可以使用无效证书的后端服务器
其他参数配置查看文档
https://webpack.docschina.org/configuration/dev-server/#devserver-proxy

请求封装

uni.docajax = function (url, data = {
    
    }, method = "GET") {
    
    
  return new Promise((resolve, reject) => {
    
    
    var type = 'application/json'
    if (method == "GET") {
    
    
      if (data !== {
    
    }) {
    
    
        var arr = [];
        for (var key in data) {
    
    
          arr.push(`${
      
      key}=${
      
      data[key]}`);
        }
        url += `?${
      
      arr.join("&")}`;
      }
      type = 'application/x-www-form-urlencoded'
    }
    var access_token = uni.getStorageSync('access_token')
    console.log('token:',access_token)
    var baseUrl = '/api/doc/'
    uni.request({
    
    
      url: baseUrl + url,
      method: 'GET',
      data: data,
      header: {
    
    
        'content-type': type,
        'Accept':'application/x..v1+json',
        'Authorization':'Bearer '+access_token,
      },
      success: function (res) {
    
    
        if (res.data) {
    
    
          resolve(res.data)
        } else {
    
    
          console.log("请求失败", res)
          reject(res)
        }
      },
      fail: function (res) {
    
    
        console.log("发起请求失败~")
        console.log(res)
      }
    })
  })
}

请求示例:

//获取用户信息
uni.docajax("userinfo",{
    
    },'GET')
.then(res => {
    
    
    this.nickname = res.nickname
    this.avatar = res.avatar
});

猜你喜欢

转载自blog.csdn.net/weixin_46351593/article/details/119972078
今日推荐