搭建axios服务器 axios请求服务器
文章目录
- Vue 中的 ajax
- 4.1 案例分析:使用axios发请求
- 4.2 vue脚手架配置代理服务器 (解决开发环境 Ajax 跨域问题)
- 4.2.1 方法一
- 4.2.2 方法二
- 4.3 vue 项目中常用的 2 个 Ajax 库
- 4.3.1 axios
- 4.3.2 vue-resource
- 4.4 插槽
Vue 中的 ajax
4.1 案例分析:使用axios发请求
案例:使用axios发请求(获取学生信息)
App.vue
<template> <div> <!-- 2 给一个点击事件获取学生信息--> <button @click="getStudents">获取学生信息</button> </div> </template> <script> // 1 引入axios import axios from 'axios' export default { name:'App', // 3 配置一个methods methods: { // 4 获取学生信息 getStudents(){ // 5 发请求 (get请求 url就是刚刚启动服务器后出现的地址,请求返回的是一个promise) axios.get('http://localhost:5000/students').then( // 成功的形参叫response,给的是响应对象,响应对象里面的data属性才是服务器真正给的东西。 失败的叫error response => { console.log('请求成功了',response.data) }, error => { console.log('请求失败了',error.message) } ) }, }, } </script>按照上面代码写,会报错
存在同源策略(协议名 主机名 端口号一致)问题,如何解决呢?
如何开启这个代理服务器的8080呢?
4.2 vue脚手架配置代理服务器 (解决开发环境 Ajax 跨域问题)
4.2.1 方法一
在vue.config.js中添加如下配置:
// 开启代理服务器 // 目前位置8080(前端),代理服务器8080,这些不用管,我们这里是代理服务器8080把请求发给谁,下面就写谁(5000) devServer:{ proxy:"http://localhost:5000" }配置好了,代理服务器,直接运行还是会报错,需要把刚刚App里面发请求的地址改成代理服务器的
App.vue
<template> <div> <!-- 2 给一个点击事件获取学生信息--> <button @click="getStudents">获取学生信息</button> </div> </template> <script> // 1 引入axios import axios from 'axios' export default { name:'App', // 3 配置一个methods methods: { // 4 获取学生信息 getStudents(){ // 5 发请求 (get请求 url就是刚刚启动服务器后出现的地址,请求返回的是一个promise) axios.get('http://localhost:8080/students').then( // 成功的形参叫response,给的是响应对象,响应对象里面的data属性才是服务器真正给的东西。 失败的叫error response => { console.log('请求成功了',response.data) }, error => { console.log('请求失败了',error.message) } ) }, }, } </script>运行之后显示:
说明:
4.2.2 方法二
编写vue.config.js配置具体代理规则:
module.exports = { devServer: { proxy: { '/api1': {// 匹配所有以 '/api1'开头的请求路径 target: 'http://localhost:5000',// 代理目标的基础路径 changeOrigin: true, pathRewrite: {'^/api1': ''} }, '/api2': {// 匹配所有以 '/api2'开头的请求路径 target: 'http://localhost:5001',// 代理目标的基础路径 changeOrigin: true, pathRewrite: {'^/api2': ''} } } } } /* changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000 changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080 changeOrigin默认值为true */说明:
4.3 vue 项目中常用的 2 个 Ajax 库
4.3.1 axios
通用的 Ajax 请求库, 官方推荐,使用广泛
4.3.2 vue-resource
vue 插件库, vue1.x 使用广泛,官方已不维护。
4.4 插槽