最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught (in promise) TypeError: response.json is not a function - Stack Overflow

programmeradmin1浏览0评论

I am trying to load a data from my firebase backend but getting this error

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

my code is as below :

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 ');
      }
    });
};

however, if I try response.data instead of response.json it works and successfully loads the data, so I am curious what the difference is and why the first one doesn't work.

I am trying to load a data from my firebase backend but getting this error

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

my code is as below :

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 ');
      }
    });
};

however, if I try response.data instead of response.json it works and successfully loads the data, so I am curious what the difference is and why the first one doesn't work.

Share Improve this question edited Nov 10, 2022 at 13:18 skr asked Dec 23, 2019 at 10:09 skrskr 1,8111 gold badge17 silver badges46 bronze badges 2
  • 3 You're using axios. Try reading the documentation for axios and not the documentation for fetch. – Quentin Commented Dec 23, 2019 at 10:17
  • @skr, please mark the answer as correct if it has solved your issue – joy08 Commented Jan 10, 2020 at 9:14
Add a comment  | 

4 Answers 4

Reset to default 7

Because of the axios package, it has a specific response schema 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: {}
}

With axios you don't need an extra .json() .Responses are already served as javascript object, no need to parse, simply get response and access data. You could use directly something like

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);
  });

You only need to use the Body.json() method if you are trying to resolve the promise from a Response stream. You may read more about it on the documentation. One use case of doing so would be when you are making a HTTP request using the fetch API, whereby you will have to call Body.json() to return the response body.

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);
}

For axios, you only need to resolve the promose after making a GET request

axios.get(url[, config])

and thus, the following code below works, as the returned response body is handled within the .then() block when you resolve the promise.

axios
  .get('data.json')
  .then(response => console.log(response.data))
const CollectData = async () => {
    let result = await fetch('http://localhost:5400/Enquiry', {
      method: "post",
      body: JSON.stringify({ name, email, contact, message }),
      headers: {
        "Content-Type": "application/json",
      }
    });
    result = await result.json();
    console.log(result);
    if (result) {
      navigate("/");
    }
发布评论

评论列表(0)

  1. 暂无评论