处理跨域请求时,不同的技术栈会有不同的实现方式。以下是一些前端使用JavaScript、Vue.js,后端使用Java,以及服务器使用Nginx处理跨域请求的示例。
前端JavaScript处理跨域
使用JSONP
function handleData(data) {
// 处理数据
console.log(data);
}
var script = document.createElement('script');
script.src = 'http://api.example.com/data?callback=handleData';
document.body.appendChild(script);
前端Vue.js处理跨域
使用Vue Resource(Vue 2.x)
this.$http.get('http://api.example.com/data').then(response => {
// 处理数据
console.log(response.body);
}, response => {
// 处理错误
console.error('请求失败:', response);
});
使用axios(Vue 2.x或3.x)
axios.get('http://api.example.com/data')
.then(response => {
// 处理数据
console.log(response.data);
})
.catch(error => {
// 处理错误
console.error('请求失败:', error);
});
后端Java处理跨域
使用Spring Boot设置CORS
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://example.com") // 允许的源
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法
.allowedHeaders("Origin", "Content-Type", "Accept") // 允许的头部
.allowCredentials(true) // 是否发送Cookie
.maxAge(3600); // 预检请求的缓存时间(秒)
}
};
}
}
Nginx处理跨域
Nginx配置文件添加CORS头部
在Nginx配置文件的server
块中添加以下指令:
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' '*';
# 其他指令...
}
这些示例展示了在不同场景下如何处理跨域请求。在实际应用中,你需要根据具体的业务需求和安全考虑来调整配置。例如,在生产环境中,通常不建议将Access-Control-Allow-Origin
设置为*
,因为这可能会暴露服务给不受信任的源。相反,应该明确列出允许的源。