持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情
为什么会出现跨域
同源策略/SOP(Same origin policy)是一种约定,由Netscape公司1995年引入浏览器,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS、CSFR等攻击。
所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个ip地址,也非同源。
解决跨域方法
1、JSONP
$.ajax({ url: '<http://www.domain2.com:8080/login>', type: 'get', dataType: 'jsonp', // 请求方式为jsonp jsonpCallback: "onBack", // 自定义回调函数名 data: {} });
JSONP的缺点 JSONP只支持 GET 请求。
2、配置nginx进行反向代理解决跨域
反向代理的原理就是讲前端的地址和后端的地址用nginx转发到同一个地址下,如5500端口和3000端口都转到3003端口下,具体配置如下:
server { listen 3003; server_name localhost; ## = /表示精确匹配路径为/的url,真实访问为http://localhost:5500 location = / { proxy_pass http://localhost:5500; } ## /no 表示以/no开头的url,包括/no1,no/son,或者no/son/grandson ## 真实访问为http://localhost:5500/no开头的url ## 若 proxy_pass最后为/ 如http://localhost:3000/;匹配/no/son,则真实匹配为http://localhost:3000/son location /no { proxy_pass http://localhost:3000; } ## /ok/表示精确匹配以ok开头的url,/ok2是匹配不到的,/ok/son则可以 location /ok/ { proxy_pass http://localhost:3000; } }
vue中解决跨域问题:
devServer: { proxy: { //配置跨域 '/api': { target: 'http://121.121.67.254:8185/', //这里后台的地址模拟的;应该填写你们真实的后台接口 changOrigin: true, //允许跨域 pathRewrite: { /* 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/api/core/getData/userInfo 时 实际上访问的地址是:http://121.121.67.254:8185/core/getData/userInfo,因为重写了 /api */ '^/api': '' } }, } },
在vue中使用proxy进行跨域的原理是:将域名发送给本地的服务器(启动vue项目的服务,loclahost:8080),再由本地的服务器去请求真正的服务