Java跨域资源共享(CORS)实践

绿茶味的清风 2024-05-25 ⋅ 23 阅读

什么是跨域资源共享(CORS)?

跨域资源共享(CORS)是一种网络浏览器机制,用于实现在不同源之间安全共享资源。当一个浏览器从一个源(网站)向另一个源发送请求时,如果两个源的协议(protocol),域(domain)或端口(port)不同,则会发生跨域请求。

在默认情况下,浏览器限制了跨域请求,以防止恶意网站诱导用户访问受害者网站。然而,对于需要在不同源之间进行数据传输的合法需求,我们可以通过配置CORS来允许浏览器执行跨域请求。

实践CORS

后端实现

在Java中,我们可以使用Spring Framework来实现CORS。首先,我们需要在后端配置允许跨域请求的相关信息。

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

在上面的示例中,我们允许来自http://example.com源的所有请求(/**)进行跨域访问。同时,我们还可以限制允许的请求方法、请求头以及请求是否可以携带凭证。

前端实现

在前端代码中,我们需要确保发送的请求中包含CORS相关的信息。以下是使用XMLHttpRequest对象实现跨域请求的示例:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api/data', true);
xhr.withCredentials = true; // 允许发送凭证信息
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        } else {
            console.error('Error:', xhr.status);
        }
    }
};

xhr.send();

上述示例代码中,我们通过设置xhr.withCredentialstrue来允许发送凭证信息,设置请求头中的X-Requested-With字段为XMLHttpRequest来确保服务器正确处理跨域请求。

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $.ajax({
        url: 'http://example.com/api/data',
        type: 'GET',
        xhrFields: {
            withCredentials: true // 允许发送凭证信息
        },
        crossDomain: true, // 允许跨域访问
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        success: function(data) {
            console.log(data);
        },
        error: function(xhr, textStatus, errorThrown) {
            console.error('Error:', xhr.status);
        }
    });
</script>

在上述示例中,我们使用了jQuery的$.ajax函数来发送跨域请求。通过设置xhrFields中的withCredentials字段为true来允许发送凭证信息,设置crossDomaintrue来允许跨域访问,并设置请求头中的X-Requested-With字段为XMLHttpRequest

总结

跨域资源共享(CORS)是一种机制,允许在不同源之间安全共享资源。在Java中,我们可以使用Spring Framework来配置CORS。在前端代码中,我们需要确保发送的请求包含CORS相关的信息,以便与后端正确处理跨域请求。通过实践CORS,我们可以在不同源之间实现安全的资源共享。


全部评论: 0

    我有话说: