简体   繁体   中英

cannot post in axios in vue.js

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

在此处输入图片说明

What wrong with it?

in web response like this

在此处输入图片说明

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);
    });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM