简体   繁体   English

使用JavaScript Fetch API执行POST请求

[英]Using the javascript fetch api to perform a POST request

I would like to reproduce the behavior of this cURL request : 我想重现此cURL请求的行为:

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

In this case, the server send me back JSON. 在这种情况下,服务器会向我发送回JSON。

The code I use in Javascript is : 我在Javascript中使用的代码是:

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

With that, I get a parsing json error, so, I decided to return response.text() instead of response.json() 这样,我得到一个解析json错误,因此,我决定返回response.text()而不是response.json()

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

It's the same string that I get when I access to the url : https://api.t411.ch/auth with my browser (GET request). 当我使用浏览器访问URL: https//api.t411.ch/auth时,得到的字符串与该字符串相同(GET请求)。

That means that my javascript code send a GET request, even with the method: 'post' 这意味着即使使用以下method: 'post' ,我的JavaScript代码也会发送GET请求method: 'post'

What am I doing bad ? 我在做什么不好?

PS: I think it's not related at all, but I use es6/jsx transpiled by babel in an electron project. PS:我认为这根本不相关,但是我在电子项目中使用了由babel编译的es6 / jsx。

Thanks 谢谢

Your code is trying to POST to https://api.t411.ch/auth/ . 您的代码正在尝试发布到https://api.t411.ch/auth/ It should be https://api.t411.ch/auth instead. 它应该是https://api.t411.ch/auth This should work fine: 这应该工作正常:

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

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

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