Java 跨域问题处理
Java 跨域问题处理
问题
在页面上要使用 Ajax
请求去获取另外一个服务的数据,由于浏览器的 同源策略,所以直接请求会得到一个 Error
。
1 | Failed to load https://www.baidu.com/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. |
大概就是这样的一个错误,关键词是 Access-Control-Allow-Origin,一般出现这个都是跨域问题。
解决方案
解决跨域问题的方式有很多,但这里之说 Cors 的方案。
在后台添加一个 Filter
过滤器
1 | /** |
在 web.xml
文件中添加拦截器配置(注:如果可能就配置成第一个 Filter
)
1 | <!--cors 跨域访问--> |
Spring Web 的解决方案
配置一个每次请求都过滤一次的 Filter
就好了
1 |
|
使用示例
下面是一些简单的使用 fetch
进行跨域请求的示例:
简单 fetch 请求,和正常使用 fetch 并无区别
1
2
3fetch(url)
.then(res => res.json())
.then(json => console.log(json))表单请求
1
2
3
4
5
6
7
8
9
10var fd = new FormData()
fd.append('username', 'rx')
fd.append('password', 'rx')
fetch(url, {
method: 'POST',
body: fd,
})
.then(res => res.json())
.then(json => console.log(json))需要认证的请求
1
2
3
4
5
6
7
8
9
10fetch(url, {
/**
* 关键就在这里,代表用户是否应该在跨域的情况下发送 cookies 和 HTTP Basic authentication 等验信息以及服务端能否返回 Set-Cookie(服务端 Session 需要使用这个向 cookie 中设置 sessionId)。
* 包含三个可选值:omit(从不发送), same-origin(同源才发送), include(总会发送)
* 参考链接:<https://developer.mozilla.org/zh-CN/docs/Web/API/Request/credentials>
*/
credentials: 'include',
})
.then(res => res.json())
.then(json => console.log(json))注:如果想要服务端返回
Set-Cookie
(SessionId
也需要通过这个响应属性去设置) 就必须设置这个请求参数!
那么,之后在前端跨域请求的时候就可以愉快地玩耍啦(v^_^)v