Java-14-解决html跨域访问Java后台问题

最近继续蛋疼啊,各种问题各种搞,本次不扯淡、开门见山。要是喜欢就评论“666”

这两天在搞html访问后台接口,发现跨域是个问题,解决这个问题需要ajax请求做配置、Java接口增加适配。

html中ajax请求:

$.ajax({
              type: "POST",
              url: "http://192.168.2.120:8093/api/getRoute",
              data: {routeKeyword:''},
              dataType: 'jsonp',//跨域访问关键配置
              jsonp:'jsoncallback',//跨域访问关键配置
              crossDomain: true,//跨域访问关键配置
              success: function (rs) {
//                  console.log(rs);
              },
              error: function( xhr, textStatus, errorThrown ) {

//                  console.log(errorThrown);
              }

Java接口

 @ResponseBody
    @RequestMapping(value = "/getRoute", method ={RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public void getAllBusRoute(HttpServletRequest request,HttpServletResponse response) throws IOException {
//         TODO 支持跨域访问
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
        response.setHeader("Access-Control-Expose-Headers", "*");

        String jsoncallback = request.getParameter("jsoncallback");// 客户端请求参数
        String result = "········";
        String routeKeyword = request.getParameter("routeKeyword");

        JSONObject rr = JSONObject.parseObject(result);
        if (rr==null){
            return;
        }

        String json = rr.getString("data");
        result = jsoncallback + "("+json+")";
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(result);
        writer.flush();
        writer.close();
    }

 

你可能感兴趣的:(JAVA)