美文网首页
VUE 跨域代理 设置proxyTable

VUE 跨域代理 设置proxyTable

作者: 精神病赛车手 | 来源:发表于2019-02-15 16:56 被阅读0次

前言

vue-cli启动本地服务,通常我们的请求地址是以localhost:8080来请求接口数据的。当浏览器报如下错误时,则说明请求跨域了。

localhost/:1 Failed to load http://www.thenewstep.cn/test/testToken.php: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

1.为什么会跨域:
因为浏览器同源策略的限制,不是同源的脚本不能操作其他源下面的对象。
2.什么是同源策略:
同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
简单的来说:协议、IP、端口三者都相同,则为同源。


域名.png

解决办法

找到config文件夹下的index.js,并设置proxyTable。

proxyTable: {
   "/api": {
      target: "http://bl.7yue.pro/v1",
      changeOrigin: true,
      pathRewrite: {
         "^/api": ""
      }
    }
}

用代理, 首先你得有一个标识, 告诉他你这个连接要用代理. 不然的话, 可能你的 html, css, js这些静态资源都跑去代理. 所以我们只要接口用代理, 静态文件用本地。

"/api":{} 就是告诉node, 我接口只要是"/api"开头的才用代理.所以你的接口就要这么写/api/classic/latest,最后代理的路径就是 http://bl.7yue.pro/v1/api/classic/latest

可是不对啊,接口地址为http://bl.7yue.pro/v1/classic/latest正确的接口路径里面没有/api啊。
所以就需要 pathRewrite,用 "^/api": "", 把'/api'去掉, 这样既能有正确标识, 又能在请求接口的时候去掉api

changeOrigin: true 表示时候跨域。

相关文章

网友评论

      本文标题:VUE 跨域代理 设置proxyTable

      本文链接:https://www.haomeiwen.com/subject/talmeqtx.html