vue发送ajax请求
发布于 3 年前 作者 lei47 1466 次浏览 来自 分享

常用发送ajax请求的方法

  • xhr
  • jQury $.get $.post
  • axios
  • fetch window内置,promise风格,会把返回数据包两层promise,而且兼容不好
  • v-resouce
//server1.js
const express = require('express')
const app = express()

app.use((request,response,next)=>{
	console.log('有人请求服务器1了');
	// console.log('请求来自于',request.get('Host'));
	// console.log('请求的地址',request.url);
	next()
})

app.get('/students',(request,response)=>{
	const students = [
		{id:'001',name:'tom',age:18},
		{id:'002',name:'jerry',age:19},
		{id:'003',name:'tony',age:120},
	]
	response.send(students)
})

app.listen(5000,(err)=>{
	if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students');
})

//server2.js
const express = require('express')
const app = express()
app.use((request,response,next)=>{
	console.log('有人请求服务器2了');
	next()
})
app.get('/cars',(request,response)=>{
	const cars = [
		{id:'001',name:'奔驰',price:199},
		{id:'002',name:'马自达',price:109},
		{id:'003',name:'捷达',price:120},
	]
	response.send(cars)
})
app.listen(5001,(err)=>{
	if(!err) console.log('服务器2启动成功了,请求汽车信息地址为:http://localhost:5001/cars');
})

服务器1为:http://localhost:5000/students
服务器2地址为:http://localhost:5001/cars

//App.vue
<template>
	<div>
		<button @click="getStudents">获取学生信息</button>
	</div>
</template>

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

这样子,会有跨域问题,当前处于http://localhost:8080,请求服务器1为:http://localhost:5000/students

什么是跨域?

浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域
主域名不同

子域名不同

端口:

协议:

备注:
 1、端口和协议的不同,只能通过后台来解决
 2、localhost和127.0.0.1虽然都指向本机,但也属于跨域

解决跨域

  • cors 写服务器的人在写服务器时给响应信息加上特殊的响应头
  • jsonp
  • 代理服务器 代理服务器在中间出现,代理服务器所处位置和请求数据端位置一样,请求方向代理服务器要数据,代理服务器向服务器要数据,然后原路返回。代理服务器和服务器之间没有跨域问题,是通过http请求(ngnix、vue-cli

vue配置代理

方式一

//vue.config.js
module.exports = {
    pages: {
      index: {
        //入口
        entry: 'src/main.js',
      },
    },
    lintOnSave:false,//关闭语法检查,
    //配置代理服务器
    devServer:{
      proxy:'http://localhost:5000'//只写到端口号就行
    }
  }
//App.vue
<template>
	<div>
		<button @click="getStudents">获取学生信息</button>
	</div>
</template>

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


说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源),如果前端有的话,代理服务器不会转发请求给服务器

方式二

协议名、主机名、端口号后面加前缀api,灵活控制走不走本地,有就让代理服务器转发,但是给服务器的地址不能带前缀

//vue.config.js
module.exports = {
    pages: {
      index: {
        //入口
        entry: 'src/main.js',
      },
    },
    lintOnSave:false,//关闭语法检查,
    devServer:{
      proxy:{
        '/api':{
          //target:'<url>',
          target:'http://localhost:5000',
          pathRewrite:{'^/api':''},//正则,重写路径,匹配所有有/api的字符串替换成空
          ws:true,//用于支持websocket
          changeOrigin:true //如果为true,告诉服务器来自和服务器同一位置(http://localhost:5000),其实就是请求头中的host信息。
        },
        '/api2':{
          //target:'<url>',
          target:'http://localhost:5000',
          pathRewrite:{'^/api2':''},
          ws:true,//用于支持websocket
          changeOrigin:true //用于控制请求中的host值
        }
      }
    }
  }
//App.vue
<template>
	<div>
		<button @click="getStudents">获取学生信息</button>
	</div>
</template>

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

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

vue-resource

和axios的使用相同,在vue1.0时较多使用

//main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate() {
		Vue.prototype.$bus = this
	},
})
	this.$http.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
					response => {
						console.log('请求成功了')
						//请求成功后更新List的数据
						this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items})
					},
					error => {
						//请求后更新List的数据
						this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]})
					}
				)
1 回复
回到顶部