Rüdiger
Rüdiger

Reputation: 943

Adjust XHR Header

I want to create an XHR in TypeScript. The API I want to access has the following url:

https://my-url/user/login

and should look like this when passing data:

https://my-url/user/login?username=username&password=password&api_key=key

My problem is, that I formed my XHR with the https://my-url/user/login - url and when passing data I received a 404 (I guess because he formed it like this https://my-url/user/login/username=username...). My workaround: passing the header directly into xor with inserted elements:

        let xhr = new XMLHttpRequest();
        xhr.open("GET", "https://my-url/user/login?username=" + username 
            + "&password=" + password + "&api_key=key", true);
        xhr.setRequestHeader("Accept", "application/json");
        // xhr.setRequestHeader("api_key", "key");
        //xhr.setRequestHeader("username", username);
        // xhr.setRequestHeader("password", password);
        xhr.onreadystatechange = function() {
            console.log("state changed - new state: " + xhr.readyState + " and Status: " + xhr.status);
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    console.log("login Request successful: " + xhr.responseText);
                    alert("Logged in!");
                } else {
                    alert("Login failed!");
                    console.log("Error: " + xhr.status + " Message: " + xhr.statusText);
                }
            }
        };
        xhr.send();

But I would like not to use this way and since there has to be a way to perform this request differently - can someone give me a hint on how to solve this?

Upvotes: 0

Views: 107

Answers (1)

kGielo
kGielo

Reputation: 381

First, do not put plain variables in request. Use encodeURIComponent (ref: Mozilla Developer)

You can use this function to properly format GET parameters.

function formatParams( params ){
      return "?" + Object.keys(params).map((key) => {
          return `${key}=${encodeURIComponent(params[key])}`
      }).join("&")
}

Then you can use it like this:

let xhr = new XMLHttpRequest();
xhr.open("GET", `https://my-url/user/login${formatParams({username, password, api_key: key})}`, true);
xhr.setRequestHeader("Accept", "application/json");

Upvotes: 1

Related Questions