0

Im working on a project, where we try to exchange different parameters between the UI and a RestAPI via AJAX. The RestAPI defines how the data has to look:

Parameters to send

enter image description here

I tried to solve it this way:

 $(document).ready(function(){
  $("#submit").click(function(){
      var credentials = [
          {user_name: $("#uname").val(),
            password: $("#pwd").val()
          }
      ];
      alert(credentials);
      $.ajax({
          url:"../rest/user/login",
          type:"POST",
          data:JSON.stringify({credentials: credentials}),
          success: function(){
            window.location.href = "startrackhome.html";
          },
          error:  function error(response){
            try{
              var json = JSON.parse(response.responseText);
              if(typeof json.message === 'undefined'){
                throw new Error("Response json has no message");
              }
              else{
                alert(json.message);
              }
            }
          catch(ex){
            alert("unexpected error (code:" + response.status +")");
          }
        }

      });
   });
   });

The alert shows this: [object Object]

And I always get an error message (error: 400), which means that I mus have made a mistake and I think the format I'm sendig is wrong but I dont know how to fix it.

I hope you can help me! :)

skywalther
  • 15
  • 4
  • I think you should not stringify the json but pass the object as is to $.ajax, and add `contentType: "application/json"` – Lk77 Jun 10 '22 at 10:00
  • I tried it but I still get the Error Message so thats not the solution I guess – skywalther Jun 10 '22 at 10:13
  • Does your server support json requests ? if not try `contentType: "application/x-www-form-urlencoded"` instead and try `data: {credentials: JSON.stringify(credentials)}` – Lk77 Jun 10 '22 at 10:24
  • As far as I know the server supports json requests (we use that for another request). But I still tried your option and it also didn't work – skywalther Jun 10 '22 at 10:31
  • Do you have an error message ? because that request is fine, it's perhaps something else, are you sure the credentials are valid ? – Lk77 Jun 10 '22 at 12:07
  • I did not get other error messages. I looked at the request payload and its this: credentials%5B0%5D%5Buser_name%5D=username&credentials%5B0%5D%5Bpassword%5D=password The response is this: SyntaxError: Unexpected token # in JSON at position 0
       at JSON.parse (<anonymous>)
       at createStrictSyntaxError
    – skywalther Jun 12 '22 at 14:05
  • Try to stringify the credentials then, perhaps it will work `data: {credentials: JSON.stringify(credentials)}`, because your payload seems to have plain credentials (not stringified) – Lk77 Jun 13 '22 at 07:31
  • After changing it to what you suggested it still looks the same – skywalther Jun 14 '22 at 15:40
  • And the payload how it looks ? you should have a credentials field with a json inside. Can you call for help in your company ? because i don't think we will be able to help you further, without knowing the implementation logic of the api, and the authentication system it's difficult to help. Check the url to be sure because `../rest/user/login` seems a bit off – Lk77 Jun 14 '22 at 15:44
  • And also remove the array of credentials, it should be an object not an array, like so : `{user_name: '', password: ''}` – Lk77 Jun 14 '22 at 15:51

1 Answers1

0

I made some changes to your code :


// credentials is an object
var credentials = {
    user_name: $("#uname").val(),
    password: $("#pwd").val()
}
alert(credentials);
$.ajax({
    // check this url seems a bit off
    url: "../rest/user/login",
    type: "POST",
    data: {
        credentials: credentials
    },
    success: function() {
        window.location.href = "startrackhome.html";
    },
    error: function error(response) {
        try {
            var json = JSON.parse(response.responseText);
            if (typeof json.message === 'undefined') {
                throw new Error("Response json has no message");
            } else {
                alert(json.message);
            }
        } catch (ex) {
            alert("unexpected error (code:" + response.status + ")");
        }
    }

});

in my case it makes this request :

fetch("https://stackoverflow.com/posts/rest/user/login", {
  "headers": {
    "accept": "*/*",
    "accept-language": "",
    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Linux\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "x-requested-with": "XMLHttpRequest"
  },
  "referrer": "https://stackoverflow.com/posts/72620005/edit",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "credentials%5Buser_name%5D=test&credentials%5Bpassword%5D=test",
  "method": "POST",
  "mode": "cors",
  "credentials": "include"
});
credentials[user_name]: test
credentials[password]: test

which seems good, if the server needs a json, you can stringify the credentials, which gives this paylaod :

credentials: {"user_name":"test","password":"test"}
Lk77
  • 2,203
  • 1
  • 10
  • 15
  • I still get the same error message and the payload is still the same. I guess I should try talking to the people that are responsible for the api. Thanks for your help so far! – skywalther Jun 14 '22 at 16:04
  • I think you have invalid credentials, it's the only explanation if you are still having issues, one of the two solutions should pass, either the json one, or the x-www-form-urlencoded one – Lk77 Jun 14 '22 at 16:05
  • I used the developer tool of chrome to find out what the problem is exactly and it says: "Unexpected token # in JSON at position 0". Can you tell me what this means? I cant find anything about it – skywalther Jun 17 '22 at 12:08