首页 > 解决方案 > 如何在 React.js Web 应用程序(前端)中捕获来自远程 URL 的 JSON 数据

问题描述

我们尝试使用 componentdidmount,在这里我们可以使用 Get 请求从 API 获取数据并在控制台上打印。但是这里我们的要求不是从 API 获取数据,我们想要捕获来自远程 url remoteurlexample.com 的数据并在控制台上打印这些值。

我们尝试过的:-

import React,{ Component } from "react";
import axios from 'axios'
class PostList extends Component{
    constructor(props) {
        super(props)
        this.state={
            posts: []
        }
    }

    componentDidMount() {
        axios.get('remoteurlexample.com',{ 'headers' : { 'Access-Control-Allow-Origin' : '*'}})
            .then(response => {
                console.log(JSON.stringify(response)) 
            })
            .catch(error => {
                console.log(error)
            })
    }


    render() {
        return (
            <div>
                List of posts
            </div>
        )
    }

}
export default PostList

它没有按预期工作

用于理解问题的示例图像:-

他是更好地理解问题的示例图像

请帮助这些人,或者让我知道这是实现它的另一种方式。

谢谢

标签: javascriptnode.jsreactjsexpresssockets

解决方案


推荐阅读