浏览器js在访问服务器中的资源时,会出现同一页面或者不同域名(协议,IP,端口)不可访问
例如:file://d://test.html页面(file协议)中通过ajax访问服务器api.test.com的接口(http协议),由于协议不同,此时会出现浏览器访问不了后台接口的问题
此时需要在服务器接口的请求头配置好,当浏览器访问时就会根据请求头判断是否可以访问
前端代码
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跨域请求示例</title>
</head>
<body>
<button onclick="sendRequest()">发送请求</button>
<div id="result"></div>
<script>
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8888/user/queryById?id=1', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('result').innerText = xhr.responseText;
}
};
xhr.send();
}
</script>
</body>
</html>
调用后台接口时报错
补充跨域过滤
java
package com.example.demo.config;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin,X-Requested-With,Content-type,Accept,Access-Token");
response.setHeader("Access-Control-Max-Age", "3600");
chain.doFilter(request, response);
}
}
再次请求,可以正常得到结果