Java前后端分離項(xiàng)目跨域問題解決方案
前言
本文將講解前后端項(xiàng)目中跨域問題的常見解決方案,其中后端基于SpringBoot,前端使用了jQuery、axios等框架用于實(shí)戰(zhàn)代碼的講解。本文將不涉及跨域的解釋和SpringBoot等框架,或者是Nginx的使用,將主要講解前后端分離項(xiàng)目中跨域問題的解決,不過如果你遇到了問題,也歡迎一起交流學(xué)習(xí)。
跨域解決
JSONP方式
這種方式只能用于Get請求,因此如果需要以Post請求方式獲取數(shù)據(jù),則可以先看后面CORS解決方式,以下就講解兩種基于JSONP原理的解決方案,首先先看后端的接口:
@RestController
@RequestMapping("/api/customer")
public class HelloController {
@GetMapping("/getAllCustomerInfo")
public String getAllCustomerInfo() {
// 返回的數(shù)據(jù)必須包含在 getAllCustomerInfo() 字符串中
// 以便在返回到前端后,可以自動執(zhí)行回調(diào)函數(shù),獲取數(shù)據(jù)
// getAllCustomerInfo() 與前端的回調(diào)函數(shù)名對應(yīng)
return "getAllCustomerInfo(" + getCustomerList() + ")";
}
private String getCustomerList() {
List<Customer> list = new ArrayList<>(Arrays.asList(
new Customer(1, "張三", "123456"),
new Customer(2, "李四", "654321"),
new Customer(3, "王五", "123123")
));
return new Gson().toJson(list);
}
}
下面就來分別講解以下兩種方式的解決方案:
js原生解決方案
// 首先設(shè)置 src 并將結(jié)點(diǎn)添加到 <head> 中
const script = document.createElement('script')
script.src = 'http://localhost:8080/api/customer/getAllCustomerInfo'
document.head.appendChild(script)
// 回調(diào)函數(shù)名與接口中返回的名字對應(yīng)
const getAllCustomerInfo = res => {
console.table(res, ['id', 'username', 'password'])
}
通過以上設(shè)置就可以在Console中看到以下結(jié)果:

jQuery的ajax解決方案
// 記得需要引入 jQuery
<script src="https://cdn.staticfile.org/jquery/1.10.0/jquery.js"></script>
$.ajax({
url: 'http://localhost:8080/api/customer/getAllCustomerInfo',
type: 'get',
dataType: 'jsonp',
jsonpCallback: "getAllCustomerInfo"
})
// 回調(diào)函數(shù)同上
const getAllCustomerInfo = res => {
console.table(res, ['id', 'username', 'password'])
}
CORS解決方案
跨域資源共享(CORS) 是一種機(jī)制,它使用額外的 HTTP 頭來告訴瀏覽器 讓運(yùn)行在一個 origin (domain) 上的Web應(yīng)用被準(zhǔn)許訪問來自不同源服務(wù)器上的指定的資源。當(dāng)一個資源從與該資源本身所在的服務(wù)器不同的域、協(xié)議或端口請求一個資源時,資源會發(fā)起一個跨域 HTTP 請求,詳細(xì)解釋請看鏈接。
后端接口中進(jìn)行設(shè)置
通過利用CORS,我們在前端只需要利用正常的ajax請求方式即可,無需再設(shè)置回調(diào)函數(shù),在這里我們使用了axios,在展示后端代碼之前,我們先看后端代碼的改變,為了區(qū)別于JSONP只能進(jìn)行Get請求,我們這里將接口改成了Post:
@RestController
@RequestMapping("/api/customer")
public class HelloController {
@PostMapping("/getAllCustomerInfo")
public List<Customer> getAllCustomerInfo(HttpServletResponse response) {
// 設(shè)置響應(yīng)頭
response.setHeader("Access-Control-Allow-Origin", "*");
// 不再需要將結(jié)果放在回調(diào)函數(shù)中
return new ArrayList<>(Arrays.asList(
new Customer(1, "張三", "123456"),
new Customer(2, "李四", "654321"),
new Customer(3, "王五", "123123")
));
}
}
然后前端代碼直接使用ajax請求即可:
// 首先需要引入 axios
<script src="https://cdn.staticfile.org/axios/0.1.0/axios.js"></script>
axios.post('http://localhost:8080/api/customer/getAllCustomerInfo')
.then(res => {
console.table(res, ['id', 'username', 'password'])
})
Nginx反向代理
關(guān)于反向代理的知識,這里不做詳細(xì)解析,感興趣的話,可以查看該鏈接。通過使用Nginx的反向代理,我們在后端接口中就可以去掉響應(yīng)頭的代碼設(shè)置:
@RestController
@RequestMapping("/api/customer")
public class HelloController {
@PostMapping("/getAllCustomerInfo")
public List<Customer> getAllCustomerInfo() {
return new ArrayList<>(Arrays.asList(
new Customer(1, "張三", "123456"),
new Customer(2, "李四", "654321"),
new Customer(3, "王五", "123123")
));
}
}
然后是nginx.conf中的修改:
server {
# 監(jiān)聽80端口, 前端不再直接訪問8080端口, 改為訪問80端口即可
listen 80;
server_name localhost;
location / {
root html;
# 添加頭
add_header Access-Control-Allow-Origin *;
# 代理轉(zhuǎn)發(fā)到8080后端端口
proxy_pass http://localhost:8080;
index index.html index.htm;
}
}
然后再將前端中訪問的接口修改為80:
// 首先需要引入 axios
<script src="https://cdn.staticfile.org/axios/0.1.0/axios.js"></script>
// 80為 http 默認(rèn)端口,可省略
axios.post('http://localhost/api/customer/getAllCustomerInfo')
.then(res => {
console.table(res, ['id', 'username', 'password'])
})
然后開啟Nginx服務(wù)器,Console中再次出現(xiàn)了我們想看到的結(jié)果:

總結(jié)
本文并沒有包括跨域問題的所有解決方案,不過相信對于大部分的跨域問題,都已經(jīng)可以解決了,本文在之后也可能會繼續(xù)更新,講解更多種解決跨域問題的方法
到此這篇關(guān)于Java前后端分離項(xiàng)目跨域問題解決方案的文章就介紹到這了,更多相關(guān)Java前后端分離跨域內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java對數(shù)據(jù)庫更新的操作方式及注意事項(xiàng)
這篇文章主要介紹了java對數(shù)據(jù)庫更新的操作方式及注意事項(xiàng),具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(7)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望可以幫到你2021-07-07
Spring Boot 整合 ShedLock 處理定時任務(wù)重復(fù)執(zhí)行的問題小結(jié)
ShedLock是解決分布式系統(tǒng)中定時任務(wù)重復(fù)執(zhí)行問題的Java庫,通過在數(shù)據(jù)庫中加鎖,確保只有一個節(jié)點(diǎn)在指定時間執(zhí)行任務(wù),它與SpringScheduler、Quartz等框架結(jié)合使用,本文介紹Spring Boot 整合 ShedLock 處理定時任務(wù)重復(fù)執(zhí)行的問題,感興趣的朋友一起看看吧2025-02-02
Java中十六進(jìn)制和十進(jìn)制之間互相轉(zhuǎn)換代碼示例
這篇文章主要給大家介紹了關(guān)于Java中十六進(jìn)制和十進(jìn)制之間互相轉(zhuǎn)換的相關(guān)資料,我們項(xiàng)目過程中總是要用到十進(jìn)制與十六進(jìn)制相互轉(zhuǎn)換的方法,需要的朋友可以參考下2023-07-07
Spring框架原理之實(shí)例化bean和@Autowired實(shí)現(xiàn)原理方式
這篇文章主要介紹了Spring框架原理之實(shí)例化bean和@Autowired實(shí)現(xiàn)原理方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-05-05

