spingboot 中的代码
项目目录结构
book实体类
package com.zzw.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author: zBei
* @description: 这里使用了一个lombok的小工具,可以省略get、set、构造函数
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
private Integer book_id;
private String book_name;
private String book_author;
private String book_press;
}
BookController控制类
package com.zzw.controller;
import com.zzw.domain.Book;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: zBei
* @description: 访问getBook
**/
@RestController
public class BookController {
@GetMapping("getBook")
public Book getBook(){
Book book = new Book();
book.setBook_id(001);
book.setBook_name("挪威的森林");
book.setBook_author("村上春树");
book.setBook_press("某某某出版社");
return book;
}
}
全局跨域配置CorsConfig
package com.zzw.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author: zBei
* @description: 该类写好之后,其他地方不需要改动即可实现全局的跨域
**/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* 解决全局跨域
* 外部服务器只要访问,http://127.0.0.1:8081/getBook,我用的是自己的本地服务器地址,
* 地址可以换成你自己的地址
* getBook是上面BookController中的getBook
* */
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer(){
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","POST","DELETE","PUT","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
};
}
}
前端中的代码
注意:
我的前端的页面在 http://127.0.0.1:5500/test.html,前端的服务器和后端的服务器中端口号不一致
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>跨域访问测试</title>
</head>
<body>
<div id="app">
<span>{{msg}}</span>
<br>
<button @click="getCors()">跨域访问</button>
<!-- status为200显示 -->
<ul v-show="status==200">
<!-- 显示的数据 -->
<li>{{bookList.book_id}}</li>
<li>{{bookList.book_name}}</li>
<li>{{bookList.book_author}}</li>
<li>{{bookList.book_press}}</li>
</ul>
</div>
<script src="vue.js"></script>
<script src="axios.js"></script>
<script>
var v = new Vue({
el:"#app",
data:{
msg:"hello",
status:0,
bookList:{ //用于接收后端返回的数据
}
},
methods:{
getCors(){
axios.get(
"http://127.0.0.1:8081/getBook" //调用后端中接口地址
).then(res=>{
//将状态码返回给页面,状态码为:200即可以显示
this.status = res.status;
//将从后端的数据返回给bookList
this.bookList = res.data;//
});
}
}
})
</script>
</body>
</html>