【问题标题】:making POST request using fetch使用 fetch 发出 POST 请求
【发布时间】:2017-06-02 02:24:31
【问题描述】:

如果不使用 vanilla js,我总是使用 jQuery 来发出 AJAX 请求。现在由于 React 已经接管,要发出 AJAX 请求,不需要使用整个 jQuery 库来发出这些请求,因此我们鼓励使用 js 内置的 fetch 方法、axios 或许多其他方法.

我一直在尝试使用fetch 发出POST 请求。我可以使用axis 制作它,但不能获取。

axios.post('https://reqres.in/api/login', {
    "email": "peter@klaven",
    "password": "cityslicka"
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
}); 

axios 代码看起来像这样,但是当我使用fetch 尝试我认为相同的东西时,它不起作用。谁能看到我错过了什么?值正在发布,但 API 返回错误,所以我一定是做错了什么。

var data = {
    "email": "peter@klaven",
    "password": "cityslicka"
}

fetch("https://reqres.in/api/login", {
    method: "POST",
    body:  JSON.stringify(data)
})
.then(function(response){ 
    return response.json(); 
})
.then(function(data){ 
    console.log(data)
});

【问题讨论】:

  • 您确定 API 需要 JSON 正文,而不是像普通形式的帖子那样进行 URL 编码吗?
  • “不起作用”是什么意思?请求没有发生吗?是否无法传达价值观?
  • @Osman 我已经更新了问题

标签: javascript ajax fetch axios


【解决方案1】:
 var headers = {
   "Content-Type": "application/json",                                                                                                
   "Access-Control-Origin": "*"
}

尝试将以上行添加到标题中。

var data = {
    "email": "peter@klaven",
    "password": "cityslicka"
}

fetch("https://reqres.in/api/login", {
    method: "POST",
    headers: headers,
    body:  JSON.stringify(data)
})
.then(function(response){ 
    return response.json(); 
})
.then(function(data){ 
    console.log(data)
});

【讨论】:

  • 您介意解释一下为什么需要添加headers 吗?
【解决方案2】:

使用arrow functions:

fetch('http://myapi.com/user/login', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-type': 'application/json',
    },
    body: JSON.stringify({
      login: login,
      senha: password
    })
  }).then(response => response.json())
  .then((responseJson) => console.log(responseJson))
}).catch(error => console.log(error));

【讨论】:

  • 将 URL 字符串改为单引号 ' 而不是 `
猜你喜欢
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-04
  • 2021-05-18
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多