0

I have try this code

axios
    .post("http://localhost:3010/user/login", {
      headers: {
        "Content-type": "application/json"
      },
      body: JSON.stringify({ username: "username", password: "password" })
    })
    .then(response => {
      this.resp = response;
    })
    .catch(e => {
      console.error(e);
    });

but response it invalid login but it work in postman

enter image description here

What wrong with it?

in web response like this

enter image description here

3
  • 2
    Why not just do a simple axios.post("http://localhost:3010/user/login", { username: "username", password: "password" }) and let Axios and Laravel handle the headers and JSON. Commented Feb 27, 2019 at 17:58
  • 1
    Why are you setting the Content-Type and why are you stringifying? Pretty sure axios sends as JSON by default. I'm guessing that it thinks you are sending an actual "String" and not a JSON Object. Commented Feb 27, 2019 at 18:06
  • looks like you've got data and options mixed up. Commented Feb 27, 2019 at 18:52

2 Answers 2

1

when you send an object using post, it gets converted to a string, so what you're effectively sending to your API endpoint is:

JSON.stringify(JSON.stringify({ username: "username", password: "password" }))

there is no need for that

Also, you don't send a body as part of the headers.

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

axios.post(url[, data[, config]])

what that means in your case is that you send three arguments, url, then data and then the options. Since the only header you send is that it is json data, and axios can take care of that for you, the options in this case are not needed so you can use just the first two parameters

axios
    .post(
      "http://localhost:3010/user/login",
      {
         username: "username",
         password: "password" 
      }
    )
    .then(response => {
      this.resp = response;
    })
    .catch(e => {
      console.error(e);
    });
Sign up to request clarification or add additional context in comments.

Comments

0

Change headers From:

headers: {
        "Content-type": "application/json"
      }

To

headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}

Now try, It worked for me

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.