我正在第一个API上使用Java + Spring + PHPmyadmin和纯HTML + JS,并试图了解ajax的工作原理,问题是我成功进行了POST,PUT和DELETE,但是当我尝试进行chrome by id ajax(类似于DELETE一个)执行chrome向我返回CORS错误
从原点“ http://localhost:8081/dices/players/id”访问“ http://localhost?{%22id%22:%22408%22}”处的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:所请求的资源上没有“ Access-Control-Allow-Origin”标头。”
我不明白为什么只有在尝试GET时才得到此信息,而其他操作却正常工作... API的完整“后部”也可以正常工作,并且已经过POSTMAN的测试。 这是我的Java CORS筛选器(我不完全知道它是如何100%工作的):
@Component
public class SimpleCORSFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
public SimpleCORSFilter() {
log.info("SimpleCORSFilter init");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, X-HTTP-Method-Override, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
}
这是我在JS中的函数(与ID删除DELETE一样,效果很好)
//GET PLAYER BY ID
function getById() {
let playerID = document.getElementById("playerID").value;
let playerToShow = {
id: playerID,
}
let shownPlayer = JSON.stringify(playerToShow);
$.ajax({
type: "GET",
url: "http://localhost:8081/dices/players/id",
contentType: "application/json",
data: shownPlayer,
success: function (data) {
document.getElementById("data").innerHTML = JSON.stringify(data);
console.log(data);
},
error: function () {
alert("Something went wrong!);
}
});
}
}
我对这一切CORS事情都迷失了,因此,谢谢您提供的任何线索!谢谢你,我的英语很抱歉!
答案 0 :(得分:0)
尝试将其添加到chain.doFilter行之前的doFilter方法中
if (request.getMethod().equals("OPTIONS")) {
resp.setStatus(HttpServletResponse.SC_OK);
return;
}