请求使用axios失败但成功获取

问题描述 投票:0回答:1

我正在尝试使用axios从我的API获取数据(此错误为400)

 axios.post('http://localhost:8086/api/login', 
   '{"username" : "user", "password" : "pwd"}', header)
 .then(response => {
        console.log(response)
 })
 .catch(error => {
      console.log(error.response)
 });

使用此代码,它正在工作,但我不想使用fetch(此处返回200)

const url = 'http://localhost:8086/api/login';
let data = '{"password":  "pwd", "username": "user"}'
let fetchData = {
    method: 'POST',
    body: data,
    headers: new Headers()
}
fetch(url, fetchData)
  .then(response => {
       console.log(response.body)
   })
   .catch((error) => {
       console.log("error")
       console.log(error)
    });

任何的想法?谢谢

reactjs axios
1个回答
1
投票

来自axios docs“

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

config是对象的位置,请参阅“请求配置”部分。因此,要使其工作,您应该将axios.post方法的第二个参数更改为object,而不是

'{"username" : "user", "password" : "pwd"}'

应该

{"username" : "user", "password" : "pwd"}

UPDATE

你应该使用它如下:

axios.post('localhost:8086/api/login', {"username" : "user", "password" : "pwd"}, header)

希望它有意义。

© www.soinside.com 2019 - 2024. All rights reserved.