springmvc项目的前后端分离使用ajax的坑

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Pruett/article/details/83927861
  1. 出现跨域问题,报错jquery-3.3.1.min.js:2 Failed to load localhost:8080/userLogin: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
    访问本地是不行的,可以参考网上 windows系统启动参数的设置,如果放在服务器上,也出现了这个问题,在spring的配置文件下加上如下内容
 <!--设置跨域请求-->
    <mvc:cors>
        <mvc:mapping path="/**/**"
                     allowed-origins="*"
                     allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
                     allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
                     allow-credentials="true" />
    </mvc:cors>

2.ajax 报错,表示数据格式不对,这是在传form表单的时候出现的错误,具体的修改方法是在ajax里面添加另外的两个属性:

 processData:false,
 contentType:false,

3.服务器提示@RequestBody对象为空,异常Required request body is missing的解决办法

在controller的方法上写@RequestBody,如果传多个值,我就写了多个requestbody,像表单绑定一样,但是 其实他会只穿过来一个值,这个值用String接受,用&间隔开,如下:

uaccount=123&upwd=123

当然如果是写了一个值,而且还报上面的错误说明是把空值传过来了,这时候就需要改为@RequestBody(required = false)
4.还有一个问题是在@RequestMapping上加了method = POST ,但是ajax中的Type也是post但是,提示传的是get,不理解,将method去掉,而且Type依旧是post ,就成功了,可能是requestbody要求的就是post的传值的原因吧

附带一个ajax和controller


        function login() {
           $.ajax( {
               type: "POST",
               url: "http://xxxxxx/userLogin",
               contentType: "application/json; charset=utf-8",
               data: {
                   "a" :"123",
                   "b":"123",
               },
//               dataType: "json",//预期服务器 返回的数据类型
               dataType: 'json',
               success : function (data) {
                   alert( data.statuscode );
                   console.log(data)
               }
           });
        }
 @RequestMapping(value = "/userLogin" )
    @ResponseBody
    public String userLogin(@RequestBody(required = false) String a ) throws Exception {
       System.out.println( a );
        HashMap<String ,Integer> map = new HashMap<>();
        //添加状态码
        map.put( StatusUtils.STATUSCODE , StatusUtils.LOGIN_SUCCESS  );
        return JSON.toJSONString(map);

    }

猜你喜欢

转载自blog.csdn.net/Pruett/article/details/83927861