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>