【问题标题】:Using the javascript fetch api to perform a POST request使用 javascript fetch api 执行 POST 请求
【发布时间】:2016-11-28 04:14:45
【问题描述】:

我想重现这个 cURL 请求的行为:

➜  % curl --data "" https://api.t411.ch/auth
{"error":"User not found","code":101}

在这种情况下,服务器将 JSON 发回给我。

我在 Javascript 中使用的代码是:

fetch('https://api.t411.ch/auth/', {
    method: 'POST'
}).then(response => {
  return response.json();
}).then(datas => {
  console.log(datas);
});

这样,我得到一个解析 json 错误,所以,我决定返回 response.text() 而不是 response.json()

console.log(datas) 打印:string(5) "1.2.4" Service 'view' wasn't found in the dependency injection container

这与我使用浏览器访问 url 时得到的字符串相同:https://api.t411.ch/auth(GET 请求)。

这意味着我的 javascript 代码发送了一个 GET 请求,即使是 method: 'post'

我做错了什么?

PS:我觉得完全没有关系,但是我在一个electron项目中使用的是babel转译的es6/jsx。

谢谢

【问题讨论】:

  • 警告:这是实验性的 javascript,支持很差。除了摆弄外,不要将其用于任何其他用途,只需使用标准的XMLHttpRequest
  • 点击该链接时收到安全警告。

标签: javascript post fetch-api


【解决方案1】:

您的代码正在尝试 POST 到 https://api.t411.ch/auth/。它应该是https://api.t411.ch/auth。这应该可以正常工作:

fetch('https://api.t411.ch/auth', {
    method: 'POST'
}).then(response => {
  return response.json();
}).then(datas => {
  console.log(datas);
});

【讨论】:

  • 哦,谢谢!并说我花了两个多小时换了一个“/”。
猜你喜欢
  • 2020-11-24
  • 1970-01-01
  • 2017-12-02
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
相关资源
最近更新 更多