Search code examples
asp.net-mvcreactjsasp.net-web-apiasp.net-identityaxios

i am trying to Login to ASP.NET Identity from react js using axios


i am trying to Login to ASP.NET Identity from react js using axios but the server give bad request error. The code of client Side is following.

var data = this.state;
data = JSON.stringify(data);
const response = axios({
  url: "http://localhost:56885/Token",
  method: "post",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  },
  data: data
});

But the same request is working in Postman:

Postman Request Body

Postman request Header


Solution

  • I was making a minor mistake. The content type was url encoded but i was sending json data. Thanks to @ADyson who identified the isue.

    Here is the correct Code.

    var data = this.state;
        var bodyData =
          "username=" +
          data.username +
          "&password=" +
          data.password +
          "&grant_type=password";
        const response = axios({
          url: "http://localhost:56885/Token",
          method: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
          },
          data: bodyData
        });
        console.log(response);