vue 跨域问题



在这里插入图片描述

1.1 开发环境

config/index.js 修改 proxyTable,高版本 vue-cli 的项目在 根目录/vue.config.js 中修改 proxy

1.1.1 proxyTable

proxyTable: {
  // 可以有多个
  '/api': {
    target: 'http://47.103.4.205:6666/',  // 目标接口域名, 注意加 http
    changeOrigin: true,  // 是否跨域
    pathRewrite: {
      // 这里理解成用 '/api' 代替 target 里面的地址,后面组件中我们掉接口时直接用 api 代替 
      // 比如我要调用 'http://47.103.4.205:6665/user/add',直接写 '/api/user/add' 即可
      '^/api': '/'
    }
  },
},

1.1.2 使用

// '/api' 不能忘,用它来匹配
// http://localhost/api/user/add 本地项目地址就转换成 http://47.103.4.205:6666/user/add
axios.get('/api/user/add').then(res => { 
	console.log(res)
})





1.2 生产环境

  将 vue 项目打包发布后,发现之前的代理配置失效了,这是因为 vue proxy 只能在开发环境使用(很蛋疼~),我们可以使用 nginx 在完成跨域。nginx 怎么安装就不再说了,直接上配置。

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

		# 这个是重点
		location /api {
            rewrite ^.+api/?(.*)$ /$1 break;
			proxy_pass http://47.103.4.205:6666/api;
        }
    }
}
指浏览器不允许当前页面的所在的源去请求另一个源的数据,源指协议、端口、名,只要这3个中有一个不同就是,如协议(http://a.baidu.com访问https://a.baidu.com)、端口(http://a.baidu.com:8080访问http://a.baidu.com:80)、(http://a.baidu.com访问http://b.baidu.com) [^1]。Vue问题有以下解决办法: ### 本地开发问题 - 配置 devServer 打开根目录的 `vue.config.js`(没有则创建,vue以前的版本有的是写在 `config/index.js`,有的写在 `webpack.config.js`,4x 版本统一在 `vue.config.js`),写入: ```javascript module.exports = { devServer: { host: 'localhost', port: 8080, https: false, open: false, proxy: { '/apiDev': { target: 'http://api.zmxy.com', changeOrigin: true, pathRewrite: { '^/apiDev': '' } } } } } ``` 之后使用 `npm run serve` 重新编译项目,以 `apiDev` 开头的 URL 就会自动转发到 `api.zmxy.com`。axios 使用示例如下: ```javascript this.axios.get('/apiDev/index/index/getDetail', { params: { id: id } }) ``` 另一种配置示例如下: ```javascript devServer: { proxy: { '/api': { target: 'http://localhost:8080/', changeOrigin: true, pathRewrite: { '/api': '' } } } } ``` 还有旧版本的配置方式,打开 `config/index.js`,在 `proxyTable` 中添写如下代码: ```javascript proxyTable: { '/api': { target: '填写请求源地址', changeOrigin: true, pathRewrite: { '^/api': '' } } } ``` ### Nginx 重定向转发防止 编辑 Nginx 配置文件: ```nginx location /api { rewrite ^.+api/?(.*)$ /$1 break; include uwsgi_params; proxy_pass https://www.api.zmxy.com; } ``` 重启 Nginx,axios 使用示例如下: ```javascript this.axios.get('/api/index/index/getDetail', { params: { id: id } }) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值