springmvc跨域设置

说明

可以使用注解逐个设定,可以可以使用配置全局设定。

CrossOrigin注解

    @CrossOrigin(origins = "http://localhost:3000")
    @RequestMapping(value="/search",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询")
    public void search(
                                   @ApiParam(value = "分页,从0开始")
                           @RequestParam(required = false,defaultValue = "0") int page,
                                   @ApiParam(value = "分页大小,默认10")
                           @RequestParam(required = false,defaultValue = "10") int size) {
        ...
    }

全局设置

@Configuration
public class ApiAuthConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
        registry.addMapping("/**").allowedOrigins("http://localhost:3000");
    }
}

jquery请求

function search() {
                $.ajax({
                    url: 'http://localhost:8082/api/search',
                    type: 'GET',
                    data: {'keyword':'java'},
                    success: function (res, status) {
                        if (status == 'success') {
                            console.log(res.data);
                            }
                    },
                    error: function (data, status) {
                        if (status == "error") {
                            console.log(data);
//                            alert(data);
                        }
                    }
                });

参考

  • Enabling Cross Origin Requests for a RESTful Web Service

你可能感兴趣的:(crossdomain,spring-mvc,springboot)