vue项目中 axios 进行前后端交互
程序员文章站
2022-06-06 20:02:40
...
axios 是一个基于promise的HTTP库,用于浏览器<script标签引入>和nodejs的,与服务器进行通信的库,简单的讲就是可以发送get,post请求
websocket 控制台安装,
npm安装方法:
- npm install axios
- npm install - -save vue-axios
在 main.js 中引入以下代码
// vue 引入 axios
import axios from 'axios'
Vue.prototype.$axios = axios;
例子:
methods: {
search: function () {
this.$axios.get('url/demo' ,{
params:
{
name: this.i_name,
time: this.i_time+'',
}
})
.then(res => {
this.contents = res;
console.log("contents:" + res)
})
.catch(function () {
console.log("失败!")
});
},
}
后台一般会出现跨域问题(后台是SpringBoot项目):
Access to XMLHttpRequest at 'http://***' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决方法:
新建一个配置类
package com.learning.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}