一、開發環境
- 框架:springboot 1.5.10.release
- 開發工具:idea
- jdk:1.8
- 前端框架:react 15.6.1
- 瀏覽器:chrome瀏覽器
二、跨域問題
本地使用ajax訪問localhost:8080端口時報錯:
failed to load http://localhost:8080/test/test.do: no ‘access-control-allow-origin' header is present on the requested resource. origin ‘null' is therefore not allowed access.
react與springboot前后端分離,react端口為3000而springboot端口為8080,跨端口訪問用尋常的ajax是無法跨域訪問的。
什么是跨域?
當客戶端向服務器發起一個網絡請求,url會有包含三個主要信息:協議(protocol),域名(host),端口號(port)。當三部分都和服務器相同的情況下,屬于同源。但是只要有一個不同,就屬于構成了跨域調用。會受到同源策略的限制。
同源策略限制從一個源加載的文檔或腳本如何與來自另一個源的資源進行交互。這是一個用于隔離潛在惡意文件的關鍵的安全機制。瀏覽器的同源策略,出于防范跨站腳本的攻擊,禁止客戶端腳本(如 javascript)對不同域的服務進行跨站調用(通常指使用xmlhttprequest請求)。
三、解決方法
(1)java后端過濾器實現cros:
在后端配置過濾器crosfilter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class corsfilter implements filter { public void init(filterconfig filterconfig) throws servletexception { } public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception { httpservletresponse httpresponse = (httpservletresponse) response; httpresponse.setheader( "access-control-allow-origin" , "http://localhost:3000" );//設置允許跨域的域名,需要發送cookie信息,所以此處需要指定具體的域名, httpresponse.setheader( "access-control-allow-headers" , "origin, x-requested-with, content-type, accept" ); httpresponse.setheader( "access-control-allow-methods" , "get, put, delete, post" ); //允許跨域的請求方式 /** * ajax請求的時候如果帶有xhrfields:{withcredentials:true}, * 那么服務器后臺在配置跨域的時候就必須要把access-control-allow-credentials這個請求頭加上去 */ httpresponse.setheader( "access-control-allow-credentials" , "true" ); //允許發送cookie信息 httpresponse.setheader( "cache-control" , "no-cache, no-store, must-revalidate" ); // 支持http 1.1. httpresponse.setheader( "pragma" , "no-cache" ); // 支持http 1.0. response.setheader("expires", "0"); chain.dofilter(request, response); } public void destroy() { // todo auto-generated method stub } } |
參考:跨域資源共享 cors 詳解——阮一峰
(2)使用代理服務器跨域訪問:
在dev.js中配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
devserver: { port: '3000' , //開發端口 host: '127.0.0.1' , //主機地址 historyapifallback: false , disablehostcheck: true , noinfo: false , stats: 'minimal' , inline: true , //開啟服務器的模塊熱替換(hmr) hot: true , // 和上文 output 的“publicpath”值保持一致 publicpath: context, proxy: { '/mytest/*' : { target: "http://localhost:8080" ,//對應后端端口 secure: false , changeorigin: true } //如果controller的requestmapping有多個這里也要對應多個 , '/test/*' : { target: "http://localhost:8080" , secure: false , changeorigin: true } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/hanziang1996/article/details/79380159/