首页 > 解决方案 > 您可以对反应组件进行 REST 调用吗?

问题描述

不要在服务器上调用 REST API,而是对 react js 组件进行休息调用。例如:

称呼

import React from 'react';

function Post(props) {

    function fetchPost() {
        fetch(`http://localhost:3000/fetch_post/${props.match.params.post_id}`,
            {
                method: "GET",
            }
        )
        .then((res) => {
            if (!res.ok) {
                return res.json().then(e => Promise.reject(e));
            }
            return res.json();
        })
        .then((res) => {
            console.log('returned: ' + res);
        })
        .catch(err => {
            console.log('error: ' + err);
        });
    }
  }
...

来自 React 组件的 REST API:

import React from 'react';

function FetchPost(props) {
   return (
        // How do I return a json object (obviously using JSON.stringify)? This return expects an HTML element
    
    );
}

export default FetchPost;

这可能吗?我删除了所有不重要的数据。

标签: javascriptreactjsapirestfetch

解决方案


推荐阅读