【问题标题】:I can't fetch data from the api using useEffect我无法使用 useEffect 从 api 获取数据
【发布时间】:2021-10-01 22:15:59
【问题描述】:

我只是在尝试实现一个 freecodecamp 教程,其中我们正在创建一个简单的 react-node 应用程序,在这里我无法从 api 获取数据,并且在我的浏览器控制台中出现此错误

Uncaught (in promise) SyntaxError: Unexpected token

这是我的 server.js 文件

const express = require("express");

const PORT = process.env.PORT || 3001;

const app = express();

app.get("/api", (req, res) => {
  res.json({ message: "Hello from server!" });
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

这是我要获取数据的文件

import React from "react";
import logo from "./logo.svg";
import "./App.css";

function App() {
  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    fetch("/api")
      .then((res) => res.json())
      .then((data) => setData(data.message));
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>{!data ? "Loading..." : data}</p>
      </header>
    </div>
  );
}

export default App;

【问题讨论】:

  • 好像您没有收到 JSON。查看浏览器开发者工具中的网络标签,了解您实际收到的内容。
  • 您也可以添加"proxy": "http://localhost:$PORT_NUMBER",然后正常使用fetch('/api'),它会将您的请求定向到“localhost::$PORT_NUMBER/api”。

标签: reactjs react-hooks use-effect


【解决方案1】:

我想你忘记使用完整域名了:

React.useEffect(() => {
    fetch("http://localhost:YOUR_PORT_NUMBER/api")
      .then((res) => res.json())
      .then((data) => setData(data.message));
  }, []);

【讨论】:

  • 我在客户端的 package.json 中设置了一个代理,其中我提到了 url
猜你喜欢
  • 2022-01-15
  • 2022-01-22
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2022-01-25
  • 2018-12-09
相关资源
最近更新 更多