簡體   English   中英

Uncaught (in promise) TypeError: response.json is not a function

[英]Uncaught (in promise) TypeError: response.json is not a function

我正在嘗試從我的 firebase 后端加載數據但收到此錯誤

Uncaught (in promise) TypeError: response.json is not a function

我的代碼如下:

import axios from 'axios';
export const loadData = ({ commit }) => {
  console.log('getting data from server...');

  axios
    .get('data.json')
    .then(response => response.json())
    .then(data => {
      if (data) {

        const stocks = data.stocks;
        const stockPortfolio = data.stockPortfolio;
        const funds = data.funds;

        const portfolio = {
          stockPortfolio,
          funds
        };
        commit('SET_STOCKS', stocks);
        commit('SET_PORTFOLIO', portfolio);
        console.log('Commit done ');
      }
    });
};

但是,如果我嘗試 response.data 而不是 response.json 它可以工作並成功加載數據,所以我很好奇有什么區別以及為什么第一個不起作用。

因為有 axios 包,所以它有一個特定的響應模式https://github.com/axios/axios#response-schema

The response for a request contains the following information.

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

如果您嘗試從Response流解析承諾,則只需使用 Body.json() 方法。 您可以在文檔中閱讀更多相關信息。 這樣做的一個用例是當您使用fetch API 發出 HTTP 請求時,您必須調用Body.json()來返回響應正文。

let response = await fetch(url);

if (response.ok) { // if HTTP-status is 200-299
  // get the response body (the method explained below)
  let json = await response.json();
} else {
  alert("HTTP-Error: " + response.status);
}

對於axios,只需要在發起GET請求后解析promose

axios.get(url[, config])

因此,下面的代碼可以工作,因為當您解決承諾時.then()返回的響應正文在.then()塊中處理。

axios
  .get('data.json')
  .then(response => console.log(response.data))

使用 axios,您不需要額外的 .json() .Responses 已經作為 javascript 對象提供,無需解析,只需獲取響應和訪問數據。 你可以直接使用類似的東西

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

const CollectData = async () => { let result = await fetch('http://localhost:5400/Enquiry', { method: "post", body: JSON.stringify({ name, email, contact, message }) ,標題:{“內容類型”:“應用程序/json”,}}); 結果 = 等待結果.json(); 控制台.log(結果); 如果(結果){ 導航(“/”); }

暫無
暫無

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

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