学习笔记:spring框架下跨域问题的解决(后端解决):
笔者大一学生,内容自学,本文内容为实践中遇到问题的记录,若是存在错误麻烦各位大佬帮忙留言指正。2020.4.25
前端技术栈:Vue框架
后端技术栈:Spring Boot
开发方式:Spring Boot+Vue实现前后端分离
-
直接使用前端vue的js里面请求后端调用方法查询数据库,并将数据信息返回,结果报错
也就是我们平时遇到的跨域问题
created() {
axios.get('http://localhost:9090/book/findAll').then(function (response) {
console.log(response);
})
解决方式1(基于注解,简单快捷):
后端框架:
- 直接在需要进行跨域的方法上加
@CrossOrigin
方法注解
@CrossOrigin
@GetMapping("/findAll")
public List<Book> findAll(){
return bookRepository.findAll();
}
解决方式2(配置类):
- 新建一个类,添加一个类注解
@Configuration
- 该类实现WebMvcConfigurer接口
- 重写addCorsMappings方法,基本内容如下:
- registry.addMapping()方法表示注册的后端映射
- allowedOrigins()方法表示允许跨域范围
- allowedMethods()方法表示允许跨域的请求类型
- allowedHeaders()表示允许发送的头信息如
content-type:"application/json"
完整代码如下:
package com.znk.springbootvue.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrosConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "DELETE", "PUT", "HEAD", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
两次请求结果如下:
跨域问题解决,顺带记录一个踩的小坑(跨域后的函数的回调)
将跨域后拿到的数据显示在前端页面
<template>
<div>
<table>
<tr>
<th>编号:</th>
<th>书名:</th>
<th>作者:</th>
</tr>
<tr v-for="items in books">
<td>{{items.id}}</td>
<td>{{items.name}}</td>
<td>{{items.author}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "Book",
data() {
return {
books: [],
}
},
created() {
axios.get('http://localhost:9090/book/findAll').then(function (response) {
console.log(response);//控制台显示
this.books = response.data;//数据返回视图
})
}
}
</script>
<style scoped>
</style>
已经拿到数据但是显示不出来,可以看见控制台报错’books’ of undefined。
原因分析:
前端拿到后端发来的数据后,当前的this指代books,数据中并没有books。
而我们需要将数据指向自己定义的books数据将其展示。
所以我们需要重新定义一个变量指代自己定义的books,将this(data()里面的books)指向_this
created() {
let _this=this;
axios.get('http://localhost:9090/book/findAll').then(function (response) {
console.log(response);
_this.books = response.data;
})
}
注意:一定要在方法前完成回调操作
刷新页面,结果如下: