Zenryo
Zenryo

Reputation: 61

axios post request to local host

I have some problems using axios to request posts from react, the code looks like this:

axios
  .post("http://localhost/priangan/api/user/login", {
    headers: {
      "Content-type": "application/json; charset=UTF-8",
    },
    data: {
      username: this.state.username,
      password: this.state.password,
    },
  }).then((response) => {
    if (response.status == 200) alert("Login Success");
  });

but when I request, there is some error in console like this, localhost is not found:

error in console

then I try using fetch, the code is like this:

fetch("http://localhost/priangan/api/user/login", {
    method: "POST",
    body: JSON.stringify({
      username: this.state.username,
      password: this.state.password,
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8",
    },
  }).then((response) => {
    if (response.status == 200) alert("Login Success");
  });

Its work, so what is my problem in using axios? thanks for helping me

Upvotes: 0

Views: 15217

Answers (1)

ShinaBR2
ShinaBR2

Reputation: 2705

You didn't use correct syntax. Let's try this.

axios.post(
  "http://localhost/priangan/api/user/login",
  {
    username: this.state.username,
    password: this.state.password,
  },
  {
    headers: {
      "Content-type": "application/json; charset=UTF-8",
    }
  }
)

So basically, axios.post accepts 3 params in the order: URL, data and options. Your provided data and headers key are invalid.

Official document: https://github.com/axios/axios#request-method-aliases

Upvotes: 1

Related Questions