【问题标题】:request fail with axios but succed with fetch请求通过 axios 失败,但通过 fetch 成功
【发布时间】:2017-12-21 15:51:34
【问题描述】:

我正在尝试使用 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)
    });

有什么想法吗?谢谢

【问题讨论】:

  • 错误是什么?
  • 如果你将一个 json 对象而不是一个字符串发布到 Axios 会发生什么?
  • axios.post 方法中的第二个参数应该是object 而不是string

标签: reactjs axios


【解决方案1】:

来自axios docs"

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

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

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

应该是

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

更新

你应该像下面这样使用它:

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

希望它有意义。

【讨论】:

  • 有了这个 axios.post('localhost:8086/api/login', [{"username" : "user", "password" : "pwd"}]) 我得到一个 405
  • @tetar 为什么使用array 作为第二个参数?您应该改用object
猜你喜欢
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
相关资源
最近更新 更多