vue 配置跨域访问

一、本地跨域:使用axios发送AJAX请求

1、安装axios并引入

npm的方式:

 npm install axios -S 或 cnpm install axios -S

2、引入使用axios
在main.js或者单独组件中引用 

import axios from ‘axios’
Vue.prototype.$axios = axios

二、配置跨域

1、在vue.config.js里配置

// 跨域的代理中转服务器服务
    proxy: {
      "/api":{   // /vue代理target
        target: 'http://10.1.XXX.XXX:8088',      // 后端接口的根目录
        // secure: true,           // 如果是 https ,需要开启这个选项,http为false
        changeOrigin: true,        // 是否跨域
        pathRewrite: {            // 是否重写路径,看代理前端路径是否与后端路径一致
        '^/api':'', //将所有含/api路径的,去掉/api转发给服务器                 
        }
      }
    },

 三、调用

<script>
import axios from 'axios'
export default {
 methods: {
  goVoice() {
   // 这里实际请求地址为http://10.1.XXX.XXX:8088/text
   axios.post('/api/text').then(res => {
     console.log(res, 'res')
   })
  }
 }
}
</script>

三、线上跨域 

server {
    listen       80;   // 监听端口号
    server_name  localhost;   // 服务器名称

    # 静态资源路径,这里的/root/path/to/dist是Vue项目build生成的dist目录所在路径
    location / {
       root   /root/path/to/dist;
       index  index.html;
    }

    # 接口转发,这里的http://example.com是接口的实际地址
    # 以/api接口为例,配置如下:
    location /api/ {
        proxy_pass http://example.com/; # 设置需要转发的具体地址
        proxy_set_header Host $host; # 设置将要发送到后端服务器的请求头部信息
    }
}

猜你喜欢

转载自blog.csdn.net/vanora1111/article/details/130830683
今日推荐