簡體   English   中英

使用JavaScript Fetch API執行POST請求

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

我想重現此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請求)。

這意味着即使使用以下method: 'post' ,我的JavaScript代碼也會發送GET請求method: 'post'

我在做什么不好?

PS:我認為這根本不相關,但是我在電子項目中使用了由babel編譯的es6 / jsx。

謝謝

您的代碼正在嘗試發布到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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM