XMLHttpRequest从java脚本调用时返回Bad Request(400),如果我从Java或Postman客户端调用它工作正常

时间:2016-09-27 03:48:04

标签: javascript java spring rest xmlhttprequest

我试图用java脚本调用Spring rest方法。 我得到了:

POST http://www.davco.com/search/loginAuthentication 400(错误请求)

下面是我的Java scrpt Code调用我有的Spring REST服务

   var userEmailId= $("#emailAddress").val();
   var userPwd= $("#userPassword").val();

    if (empty(userPwd)) {
        alert("Please enter password");
        return false;
    }

    var http = new createXMLHttpRequest();
    var url = "/search/loginAuthentication";
    var params = 'eid=' +userEmailId+'&pwd='+userPwd

    http.open("POST", url, true);
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/xml");
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    http.send(params);

enter image description here 当我尝试从Google Postman客户端调用相同的方法时,我能够点击服务并获得响应..

当我从Javascrpt调用它时,我无法理解我在做什么错。我已经引用了此linklink as well

我尝试了不同的 Content-type 标题,如:

http.setRequestHeader(“Content-type”,“text / html”); http.setRequestHeader(“Content-type”,“application / json”); http.setRequestHeader(“Content-type”,“Accept = application / xml”);

我从浏览器请求中看到,请求POST调用的有效负载如下所示:

enter image description here

以下是我的Spring Rest服务代码:

@RequestMapping(method = RequestMethod.POST, value = "/loginAuthentication" ,headers = "Accept=application/xml, application/json, text/html")
    public @ResponseBody String loginAuthnticationForHTEtb(@RequestParam("eid") String userEmailId,@RequestParam("pwd") String password
            ,HttpServletRequest request, HttpServletResponse response) {   

        StringBuffer result = new StringBuffer();
        try {
            String domainVraiable=Context.getDomainName();
            int inxexOfDot=domainVraiable.indexOf(".")+1;
            int lastIndexOf=domainVraiable.lastIndexOf(".");

            ....

我只是想知道为什么它正常工作,我能够从PostMan客户端调用但是在我尝试从java脚本调用时无法工作?正如您在下面的屏幕截图中看到的那样。

enter image description here

提前感谢您提供任何线索或信息以摆脱这种情况。我花了差不多一天但是想不通。

2 个答案:

答案 0 :(得分:0)

试一试:

var params = {
   eid:userEmailId,
   pwd:userPwd
};

http.send(params);

或:

 var formData = new FormData();
    formData.append("eid", userEmailId);
    formData.append("pwd", userPwd);

    http.send(formData);

答案 1 :(得分:0)

花了很多时间后,我仍然无法弄清楚上述实施中究竟出现了什么问题。

但是现在我改变了这样,并且在以下风格下正常工作:

var response = $.post("/search/loginAuthentication",{"eid":userEmailId, "pwd" :userPwd},
        function(data,status){
                processAuthenticationResponse(data);    
        },'json');
    }