Reputation: 61
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:
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
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