我无法使用 useEffect 从 api 获取数据

I can't fetch data from the api using useEffect

我只是想实现一个 freecodecamp 教程,我们在其中创建了一个简单的反应节点应用程序,在这里我无法从 api 获取数据,我得到了这个我的浏览器控制台出错

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

这是我的 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;

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

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