【问题标题】:Getting data from public API in server and send to Client从服务器中的公共 API 获取数据并发送到客户端
【发布时间】:2021-06-03 12:52:25
【问题描述】:

这是另一个可能很简单的问题,但仍然让我很困惑。我非常熟悉在前端进行 api 调用并显示数据,但是我想保证安全,所以我试图将 api 调用移动到后端服务器文件。我似乎在显示来自后端的 API 调用发送到前端的信息时遇到了一些困难。实际上,调用服务器的客户端功能在控制台中显示为挂起。数据正在控制台中登录,并且工作正常,但是如何在前端检索该数据?有问题的函数是 loadProfile 函数。

服务器文件;

const express = require('express');
const router = express.Router();
require('dotenv').config();
const axios = require('axios');

router.get('/profile', async (req, res) => {
  try {
    const data = await axios.get(
      `https://finnhub.io/api/v1/news?category=general&token=${process.env.API_KEY}`
    );

    console.log(data);
  } catch (error) {
    console.log(error);
  }
});

module.exports = router;

客户端:

import React, {useEffect, useState} from 'react';
import axios from 'axios';
import NewsCard from '../News/NewsCard';
import Post from '../Post/Post';
import PostForm from '../PostForm/PostForm';
import './Profile.css';

const Profile = () => {
  const [items, setItems] = useState([]);
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    loadProfile();
    getPosts();
  }, []);

  const loadProfile = async () => {
    const res = await axios.get('http://localhost:4000/profile');
    console.log(res.data);
    setItems(res.data);
  };

  const getPosts = async () => {
    try {
      const res = await axios.get('http://localhost:4000/post');
      setPosts(res.data);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <section className="profileBody">
      <div className="news">
        <NewsCard key={posts.idPosts} items={items} />
      </div>

      <div className="postSection">
        <PostForm getPosts={getPosts} />
        <h1>
          Latest Posts{' '}
          <span onClick={getPosts}>
            <i class="fas fa-redo"> </i>
          </span>
        </h1>

        <div>
          <Post key={posts.id} posts={posts} />
        </div>
      </div>
      <div className="prices">
        <h3>hewiorhewioajroiewja</h3>
      </div>
    </section>
  );
};
export default Profile;

【问题讨论】:

    标签: javascript node.js reactjs api


    【解决方案1】:

    您似乎没有从后端 return res.json(data); 返回响应:

    router.get('/profile', async (req, res) => {
      try {
        const data = await axios.get(
          `https://finnhub.io/api/v1/news?category=general&token=${process.env.API_KEY}`
        );
    
        console.log(data);
        return res.json(data); // missing return
      } catch (error) {
        console.log(error);
      }
    });
    

    【讨论】:

    • 谢谢...当我添加返回时,我收到一个类型错误,上面写着:TypeError: Converting circular structure to JSON --> 从带有构造函数“ClientRequest”的对象开始 |属性 'socket' -> 带有构造函数 'TLSSocket' 的对象 --- 属性 '_httpMessage' 在 stringify (/Users/jenki/Desktop/Desktop/Personal Projects/socialMediaStock/server/) 处关闭 JSON.stringify () 的圆圈node_modules/express/lib/response.js:1123:12)
    • api/v1/news?返回什么格式的数据?
    • 从文档看来它应该是一个对象数组
    • 所以我找到了另一个人的解决方案,涉及在通话后使用 .then 。我想我很困惑,因为我认为当你等待一些你不需要使用的东西时。然后
    猜你喜欢
    • 2020-08-16
    • 1970-01-01
    • 2022-01-12
    • 2013-04-11
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多