vue代理服务器解决开发环境 Ajax 跨域问题

现在有个接口localhost:5000/students,可以获取学生信息

现在vue写一个按钮获取学生信息

 因为游览器的协议规定,不同端口导致跨域问题

解决方案一

使用代理服务器,首先在项目中创建配置文件

vue.config.js的配置内容

module.exports={
    pages:{
        index:{
            // 入口
            entry:'src/main.js',
        },
    },
    lintOnSave:false, // 关闭语法检查
    // 开启代理服务器
    devServer:{
        proxy:'http://localhost:5000'
    }
}

改为本地端口 

效果

方案二

如果有多个不同端口的服务器,那么方案一就不太能满足多个服务器。

vue.config.js的配置内容

module.exports={
    pages:{
        index:{
            // 入口
            entry:'src/main.js',
        },
    },
    lintOnSave:false, // 关闭语法检查
    // 开启代理服务器(方法一)
    // devServer:{
    //     proxy:'http://localhost:5000'
    // }
    // 开启代理服务器(方法二)
    devServer:{
        proxy:{
            '/api1':{
                target:'http://localhost:5000',
                pathRewrite:{'^/api1':''}, // 重写uri,替换为空字符串
                ws:true, // 用于支持websocker
                changeOrigin:true // 用于控制请求头的host值
            },
            '/api2':{
                target:'http://localhost:5001',
                pathRewrite:{'^/api2':''}, // 重写uri,替换为空字符串
                ws:true, // 用于支持websocker
                changeOrigin:true // 用于控制请求头的host值
            }
        }
    }
}

改写访问路径

<template>
  <div id="app">
   <button @click="getStudents">获取学生信息</button>
   <button @click="getCars">获取汽车信息</button>
  </div>
</template>

<script>

import axios from 'axios'
	export default{
		name: 'App',
		methods:{
			getStudents(){
				axios.get('http://localhost:8080/api1/students').then(
					response=>{
						console.log('请求成功',response.data)
					},
					error=>{
						console.log('请求失败',error.message)
					}
				)
			},
			getCars(){
				axios.get('http://localhost:8080/api2/cars').then(
					response=>{
						console.log('请求成功',response.data)
					},
					error=>{
						console.log('请求失败',error.message)
					}
				)
			}
		}
	}

</script>

效果

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值