网站建设公制度,重庆必去的十大景点,企业网站建设价格,龙江人社app二维码图片Axios简介与安装
Axios是一个基于promise的网络请求库#xff0c;作用于node.js和浏览器中Axios在浏览器端使用XMLHttpRequests发送网络请求#xff0c;并自动完成json数据的转换安装#xff1a;npm install axios官方文档#xff1a;https://www.axios-http.cn/
Axios基…Axios简介与安装
Axios是一个基于promise的网络请求库作用于node.js和浏览器中Axios在浏览器端使用XMLHttpRequests发送网络请求并自动完成json数据的转换安装npm install axios官方文档https://www.axios-http.cn/
Axios基础语法
get请求
当参数比较少时直接在路径里面用问号拼接传入。 then里面的是个回调函数原始形态是如下 axios.get(/user?id1234).then(function(response){//处理成功的情况走then里面的函数console.log(response);}).catch(function(error){//处理错误的情况走catch里面的函数console.log(error);}).then(function(){//总会执行这里面的函数});当参数比较多时可以使用params传入。 axios.get(/user,{params:{id:12345}}).then(function(response){//处理成功的情况走then里面的函数console.log(response);}).catch(function(error){//处理错误的情况走catch里面的函数console.log(error);}).then(function(){//总会执行这里面的函数});但因为回调函数的作用域改变如果想要在axios里面使用this指针会报错undefinded所以更经常的是如下箭头函数的形式使得回调函数的作用域和其父级相同。
axios.get(/user/findAll).then((response) {console.log(response);}).catch(function (error) {console.log(error);}).then(function () {console.log(请求成功发送);});post请求
axios会自动把请求体里的数据在这里即username和password字段转成json后传给后端。
axios.post(/user,{username: shanshan,password: 12345}).then(function(response){//处理成功的情况走then里面的函数console.log(response);}).catch(function(error){//处理错误的情况走catch里面的函数console.log(error);}).then(function(){//总会执行这里面的函数});支持async/await用法 async function getUser() {try {const response await axios.get(user?id12345);console.log(response);} catch (error) {console.error(error);}}跨域问题
同源策略与CORS
同源策略为了保证浏览器的安全不同源的客户端脚本在没有明确授权的情况下不能读写对方资源。同源即两个页面具有相同的协议、主机、端口号。为了解决跨域问题CORS制定了一个技术标准使得可以在不破坏既有规则的前提下通过后端服务器实现CORS接口从而实现跨域通信。CORS将请求分为两类简单请求和非简单请求。
GET、POST、application/x-www-form-urlencoded、multipart/form-data、text/plain等常见的请求属于简单请求。 在后端的controller类上面加一个CrossOrigin注解即可使得控制器内所有请求都通过跨域问题。
Axios引入与使用
在main.js里写上
import axios from axios;
axios.defaults.baseURL http://localhost:8088
Vue.prototype.$http axios在App.vue里发送axios请求一般在页面被挂载前就发送
export default {name: App,data: function () {return {movies: [{ id: 1, title: 金刚狼1, rating: 8.7 },{ id: 2, title: 金刚狼2, rating: 8.8 },]}},created: function () {this.$http.get(/user/findAll).then((response) {console.log(response);}).catch(function (error) {console.log(error);}).then(function () {console.log(请求成功发送);});},mounted: function () {console.log(app被挂载完毕);},components: {Movie}
}