简体   繁体   English

无法在 vue.js 中的 axios 中发布

[英]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:当您使用 post 发送对象时,它会被转换为字符串,因此您有效地发送到 API 端点的是:

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 https://github.com/axios/axios#request-method-aliases

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

what that means in your case is that you send three arguments, url, then data and then the options.在您的情况下,这意味着您发送三个参数,url,然后是数据,然后是选项。 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由于您发送的唯一标头是 json 数据,并且 axios 可以为您处理,因此不需要这种情况下的选项,因此您可以只使用前两个参数

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现在尝试,它对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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