springmvc跨域設置

說明

可使用註解逐個設定,能夠可使用配置全局設定。java

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);
                        }
                    }
                });

參考

相關文章
相關標籤/搜索