yogjun / myblog

0 stars 0 forks source link

跨域请求 #11

Closed yogjun closed 5 years ago

yogjun commented 6 years ago

1JsonP jsonP并非XHR,所以jsonP只能使用GET传递参数 2代理文件 3CORS协议 http://www.ruanyifeng.com/blog/2016/04/cors.html

CORS常见header

CORS具有以下常见的header的例子:

Access-Control-Allow-Origin: http://kbiao.me Access-Control-Max-Age: 3628800 Access-Control-Allow-Methods: GET,PUT, DELETE Access-Control-Allow-Headers: content-type “Access-Control-Allow-Origin”表明它允许”http://kbiao.me “发起跨域请求 “Access-Control-Max-Age”表明在3628800秒内,不需要再发送 预检验 请求,可以缓存该结果(上面的资料上我们知道CROS协议中,一个AJAX请求被分成了第一步的 OPTION预检测请求和正式请求)。 “Access-Control-Allow-Methods”表明它允许GET、PUT、DELETE的外域请求。 “Access-Control-Allow-Headers”表明它允许跨域请求包含content-type头

当前端要请求跨域资源时候,给它加上响应的响应头即可。

Sping 4中更优雅的办法,Spring从4.2开始提供了非常方便的实现跨域的方法,对CORS提供了完整支持 @CrossOrigin(origins = "http://domain2.com", maxAge = 3600) @RestController @RequestMapping("/account") public class AccountController {

@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
    // ...
}

@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
public void remove(@PathVariable Long id) {
    // ...
}

}

Spring Boot中的用法 在Spring Boot中集成了Spring所有原生功能外,还提供了一个非常简单的外部配置方式即通过Spring Boot的全局配置文件application.properties来配置全局CORS生效: endpoints.cors.allowed-origins=http://www.xxx.com endpoints.cors.allowed-methods=GET,POST,PUT,DELETE 也可以在入口函数上添加@CrossOrigin注解来实现跨域:

@SpringBootApplication
@CrossOrigin(origins = { "http://www.xxx.com" }, methods = { RequestMethod.GET, RequestMethod.PUT, RequestMethod.POST,
        RequestMethod.DELETE })
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}