uniapp引用外部js_详解vue或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

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 上,可以使用无效证书的后端服务器

请求封装

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

});

到此这篇关于详解vue或uni-app的跨域问题解决方案的文章就介绍到这了,更多相关vue或uni-app的跨域问题解决方案内容请搜素脚本之家以前的文章或下面相关文章,希望大家以后多多支持脚本之家!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值