CORS介绍
跨域资源共享 (CORS)是一个被绝大部分浏览器实现的W3C标准,CORS允许你灵活的指定跨域请求是否授权而不是使用一些不安全脆弱的方法,例如IFRAME或者JSONP。
CORS实现方法一
MyConfiguration.java
package com.example.demo.config;
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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
//添加允许跨域访问的网站
registry.addMapping("/cors_req/**").allowedOrigins("http://dennis-dzqapp.rhcloud.com","http://localhost:8080");
}
};
}
}
或者MyConfiguration2.java
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyConfiguration2 extends WebMvcConfigurerAdapter{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/cors_req/**").allowedOrigins("https://dennis-dzqapp.rhcloud.com","http://localhost:8080");
}
}
CorsController.java
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value="/cors_req")
public class CorsController {
@RequestMapping(value="/greeting")
public String greeting(){
return "hello,CorsController";
}
}
application.properties
server.port=9999
验证代码
$.ajax({
url: "http://localhost:9999/cors_req/greeting",
type: "POST",
data: {
},
success: function(data, status, xhr) {
console.log(data);
alert(data);
}
});
使用http://dennis-dzqapp.rhcloud.com异步调用/cors_req/greeting rest api服务
cors实现方法二
CorsController2.java
package com.example.demo.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value="/cors_req2", method = RequestMethod.POST)
public class CorsController2 {
@CrossOrigin(origins = "http://dennis-dzqapp.rhcloud.com")
@RequestMapping(value="/greeting")
public String greeting(){
return "hello,CorsController2";
}
}