跨域问题解决 (设置代理)

来源:   https://www.cnblogs.com/l-y-h/p/11815452.html

 


一、什么是跨域

1、跨域

  指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。

2、同源策略

  是指协议,域名,端口都要相同,其中有一个不同都会产生跨域,在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问。

3、跨域问题怎么出现的

  开发一些前后端分离的项目,比如使用 SpringBoot + Vue 开发时,后台代码在一台服务器上启动,前台代码在另外一台电脑上启动,此时就会出现问题。
  比如:

    后台 地址为 http://192.168.70.77:8081
    前台 地址为 http://192.168.70.88:8080
  此时 ip 与 端口号不一致, 不符合同源策略,造成跨域问题。


二、使用 axios 演示并解决跨域问题(vue-cli3.0)

1、项目创建、与 axios 的使用

(1)step1:创建 vue 项目
  参考 https://www.cnblogs.com/l-y-h/p/11241503.html

(2)step2:使用 axios

  参考 https://www.cnblogs.com/l-y-h/p/11656129.html

2、跨域问题重现

(1)step1:删去 vue 项目初始提供的部分代码,如下图

 

 

运行截图:

 

 

(2)step2:使用 axios

【App.vue】
<template>
    <div>
        <button @click="testAxios">TestAxios</button>
    </div>
    <!--App -->
</template>

<script>
    // 引入axios
    import Axios from 'axios'

    export default {
        methods: {
            testAxios() {
                const url = 'https://www.baidu.com/'

                Axios.get(url).then(response => {
                    if (response.data) {
                        console.log(response.data)
                    }
                }).catch(err => {
                    alert('请求失败')
                })
            }
        }
    }
</script>

<style>

</style>

 

此时点击按钮,会出现跨域问题。

 

 

(3)常见错误解决

复制代码
【question1:】
 'err' is defined but never used (no-unused-vars)
 
 这个问题,是由于 vue 项目安装了 ESLint 。
 
 暴力解决:直接关闭 ESLint
 在  package.json 文件中 添加 
 "rules": {
    "generator-star-spacing": "off",
    "no-tabs":"off",
    "no-unused-vars":"off",
    "no-console":"off",
    "no-irregular-whitespace":"off",
    "no-debugger": "off"
}
复制代码

 

 

3、解决跨域问题

(1)step1:配置 baseURL
  可以自定义一个 js 文件,也可以直接在 main.js 中写。

【main.js】
import Vue from 'vue'
import App from './App.vue'
// step1:引入 axios
import Axios from 'axios'

Vue.config.productionTip = false

// step2:把axios挂载到vue的原型中,在vue中每个组件都可以使用axios发送请求,
// 不需要每次都 import一下 axios了,直接使用 $axios 即可
Vue.prototype.$axios = Axios

// step3:使每次请求都会带一个 /api 前缀 
Axios.defaults.baseURL = '/api'

new Vue({
  render: h => h(App),
}).$mount('#app')
 

(2)step2:修改配置文件(修改后要重启服务)
  vue 3.0 通过 vue.config.js 文件 修改配置(若没有,则直接在项目路径下新建即可)。

【vue.config.js】
module.exports = {
    devServer: {
        proxy: {
            '/api': {
                // 此处的写法,目的是为了 将 /api 替换成 https://www.baidu.com/
                target: 'https://www.baidu.com/',
                // 允许跨域
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    }
}
复制代码

 

(3)step3:修改 axios 使用方式

 
【App.vue】
<template>
    <div>
        <button @click="testAxios">TestAxios</button>
    </div>
    <!--App -->
</template>

<script>
    export default {
        methods: {
            testAxios() {
                // 由于 main.js 里全局定义的 axios,此处直接使用 $axios 即可。
                // 由于 main.js 里定义了每个请求前缀,此处的 / 即为 /api/, 
                // 经过 vue.config.js 配置文件的代理设置,会自动转为 https://www.baidu.com/,从而解决跨域问题
                this.$axios.get('/').then(response => {
                    if (response.data) {
                        console.log(response.data)
                    }
                }).catch(err => {
                    alert('请求失败')
                })
            }
        }
    }
</script>

<style>

</style>
复制代码

 

重启服务后,点击按钮,可以成功访问。

 

 

 

 

实战后记:

vue.config.js  文件 代理写法

devServer: {

proxy: {
'/ajax2': {
target: 'http://m.maoyan.com',
changeOrigin: true ,     // 允许跨域
secure: false, // 设置支持https协议的代理
},
'ajax/': {
target: 'http://m.maoyan.com',
changeOrigin: true,
pathRewrite: {                #pathRewrite这个是过滤uri里/tool开头的字符 
'^/tool': ''
}
},
}
 
如: 代理后请求 192.168.1.1/uuu    但是实际请求时 uri 为 192.168.1.1/tool/uuu  就可以加上pathRewrite过滤掉/tool
 
说明: https://segmentfault.com/a/1190000016199721
 
在封装axios时 发现 加了   ConfieBaseUrl =~!@#¥%  hots 后 不走代理了,看网上说是有个啥优先级问题 配置了就不走代理-----------------------------------------------严重踩坑第二次!!!!!!! 设置代理不要制定host 不然代理不会生效

 

 

解决方法:
封装时去掉 ConfieBaseUrl 设置
在api层调用时,传url 带上对应的 host 即可
export const getLoginRequest = params => request('post', BaseUrlhost+'api/login/', params);    (不走代理)
export const getLoginRequest = params => request('post', 'api/login/', params); (走代理)
 
另外一种待实践
baseURL 变成request方法要传的形参
 
设置一个ConfieBaseUrlinfo,当方法不传的时候 就默认这个,当调用api baseURL传入空 那么 默认的
baseURL就会不存在,可以正常走代理
var ConfieBaseUrlinfo = 'https://baidu.com/';

踩坑后记:

按上面的方法配置后发现还是不行,是因为压根不是读的你自己创建的配置文件

首先要看下你运行项目时读的是什么文件,找到这个文件

 

然后找到 devServer 下面的代理配置 proxy 看他你哪里读取的 ,原来是读区 config文件的 dev 下面的 proxyTable

 

 找到config文件位置 ,在vue里面如果直接找config文件 文件夹里面木有 那么就默认读取index文件

 

 

index文件,找到后 写入配置,这里有点不一样,他的语法见下面

 

proxyTable: {
'/tool': {
target: 'http://192.168.108.235:8280',
pathRewrite: { '^/api': '' },
},
},
 
和上面的一样写也可以

 

 

 

 语法: https://webpack.docschina.org/configuration/dev-server/#devserverproxy

 

 

后记:

上面的其实一个是vue生成的脚手架

一个是 webpack生成的.    https://segmentfault.com/a/1190000016199721

https://www.cnblogs.com/kaibindirver/p/13303464.html   

设置代理 是在 根目录下配置config 的代理文件即可(默认读取根目录vue.config.js )

 

 

如果后端是自己写的话后端也可以解决跨域

传送门: https://www.cnblogs.com/kaibindirver/p/15527052.html

 

 

 

当前端要发布线上时,代理配置如下

sudo npm i http-proxy-middleware -- save

 

根目录的 server.js 

var path = require('path')
var express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');   #加这句
var app = express();
const PORT = 11911;

#加下面的方法
app.use(
  '/con',
  createProxyMiddleware({
    target: 'https://cone-meter-dashboard.codemao.cn/',
    changeOrigin: true,
    pathRewrite: { '^/con': '' }
  })
);

 

后面发现代理的时候 接口请求码会308,需要加上 https等的属性

  devServer: {
    port: 11911,
    https: true, // 允许https接口代理
    open: true, 
    hotOnly: true, // 热更新
    proxy: {
      '/con': {
      target: 'https://dev-cone-meter-dashboard.codemao.cn/',
      changeOrigin: true,
      pathRewrite: { '^/con': '' },
      secure: false,
      },
    }
    },

 

posted @ 2021-01-05 14:31  凯宾斯基  阅读(855)  评论(3编辑  收藏  举报