前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。
跨域问题报错:
Access to XMLHttpRequest at 'http://xx.xx.xx.xx/getUser' from origin
'http://ergouzi.fun' has been blocked by CORS policy:
The 'Access-Control-Allow-Origin' header contains multiple values
'http://ergouzi.fun, *, http://ergouzi.fun', but only one is allowed.
1. 为了解决跨域问题,我在服务端代码中加了个过滤器:
package gentle.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 解决跨域设置
* (可把此设置放在 nginx 中,但只能设置一处)
*
* @author silence
* @date 2018/12/11 15:19
*/
@WebFilter(filterName = "requestFilter", urlPatterns = {"/*"})
public class RequestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// 此处 setHeader、addHeader 方法都可用。但 addHeader时写多个会报错:“...,but only one is allowed”
// response.setHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
// 解决预请求(发送2次请求),此问题也可在 nginx 中作相似设置解决。
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Cache-Control,Pragma,Content-Type,Token, Content-Type");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
String method = request.getMethod();
if (method.equalsIgnoreCase("OPTIONS")) {
servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
}
}
2. 同时在 nginx 中也作了相关配置:
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Content-Type';
...
3. 运行报错如题。
4. 解决:此错表示设置重复,只允许设置一种,去除多余设置,保留一种即可。选择第1点中方法,或者第2点中方法都可以。
----------------------------------------------------------------------------
跨域相关知识点解说: https://blog.csdn.net/jiangyu1013/article/details/84315748
PS 跨域问题解决也见文章 :解决跨域问题:No 'Access-Control-Allow-Origin' header is present on the requested resource.