JAVA服务器实现可跨域访问

ps:ajax跨域请求 放弃使用POST + JSON

原先写法POST + JSON,怎么试都不能访问

 @ResponseBody
    @RequestMapping(value = "/public/courseware/apply", method = RequestMethod.POST)
    public Object apply(@RequestBody Courseware params, HttpServletResponse response) {
        try {
            response.addHeader("Access-Control-Allow-Origin", "*");
             ...
            return ResponseObject.success();
        } catch (InvalidFieldException e) {
             ...
            return ResponseFailureObject.getErrorMessage(e);
        } catch (Exception e) {
            ...
            return ResponseFailureObject.commonError();
        }
    }

放弃JSON请求方式修改如下

 @ResponseBody
    @RequestMapping(value = "/public/courseware/apply", method = RequestMethod.POST)
    public Object apply(HttpServletResponse response,
                                  @RequestParam(value = "name") String name,
                                  @RequestParam(value = "mobile") String mobile,
                                  @RequestParam(value = "email") String email) {
        try {
            response.addHeader("Access-Control-Allow-Origin", "*");
            ...
            return ResponseObject.success();
        } catch (InvalidFieldException e) {
             ...
            return ResponseFailureObject.getErrorMessage(e);
        } catch (Exception e) {
             ...
            return ResponseFailureObject.commonError();
        }
    }

修改后可以成功访问。

你可能感兴趣的:(JAVA服务器实现可跨域访问)