为什么我无法在控制台中显示 api 的内容(出现 401 错误)?

Why can't I display the contents of an api in the console (getting 401 error)?

我想在控制台中显示此 api 的内容,但它不起作用。

我做错了什么,我该如何解决?

我得到的错误:

Error: Request failed with status code 401

这是我的代码:

import React, { Component } from 'react';
import axios from 'axios';

class Flights extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                console.log("API Call ====> " + response);
            }).catch(error => {
                console.log(error);
        })
    }

    render() {
        return(
            <div></div>
        );
    }
}

export default Flights;

您可以使用JSON.stringify()方法在打印前将响应内容解析为字符串。

这是演示:https://codesandbox.io/s/m4nq5lrxxp

另一种方法是直接打印它:

 axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then(response => {
        console.log(response.data);   // like this without string concatenation
      })
      .catch(error => {
        console.log(error);
      });