NodeJS 无法连接react到后端节点js server express

pes8fvy9  于 2023-03-29  发布在  Node.js
关注(0)|答案(1)|浏览(140)

我是一个初学者,我试图了解端口和服务器端连接与Reactjs.我一直在阅读一篇文章,并试图连接Reactjs到节点express.React端口是http://localhost:5174在文章中,他们列出了如何连接后端到React的步骤,我已经做了同样的,但它没有工作,任何人可以帮助我吗?
// App.jsx

import { useState, useEffect } from "react";
import Task from "./Task";
import "./App.scss";

function App() {
  //Value of Input
  const [val, setVal] = useState("");
  const [todos, setTodos] = useState([]);
  const [message, setMessage] = useState("");

  const addTodos = (e) => {
    if (val == "") return;
    e.preventDefault();
    setTodos([...todos, val]);
    setVal("");
  };

  useEffect(() => {
    fetch("http://localhost:5174/message")
      .then((res) => res.json())
      .then((data) => setMessage(data.message));
  }, []);

  const handleDelete = (id) => {
    setTodos(todos.filter((_, key) => key !== id));
  };

  return (
    <div className="App">
      {/** On change values*/}
      <form onSubmit={addTodos}>
        <input
          onChange={(e) => setVal(e.target.value)}
          value={val}
          type="text"
        />
        <button type="submit">Add</button>
      </form>
      <ul>
        {todos.map((todo, key) => (
          <Task todo={todo} key={key} myKey={key} handleDelete={handleDelete} />
        ))}
      </ul>
      {message + " Iam from the backend"}
    </div>
  );
}

export default App;

//Server -> server.js
const express = require("express");
const cors = require("cors");

const app = express();
app.use(cors());
app.use(express.json());

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

app.listen(5174, () => {
  console.log(`Server is running on port 5174.`);
});


PS: All the dependencies are installed

//package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.22"
  }
}
0md85ypi

0md85ypi1#

正如在聊天中所讨论的,下面是问题的解决方案
首先,您需要在服务器端代码中定义一个端点,如下所示:

app.get("/message", (req, res) => {
  res.json({ message: "This is a test message from server!" });
});

然后你可以在你的React应用中定义一个proxy,它指向你的服务器,如下所示:

// client/package.json

...
"proxy": "http://localhost:5134",
...

接下来,您需要更新fetch方法调用/message终结点,它应该可以正常工作。请确保服务器已启动并正在运行。
参考链接-Create react app with node backend

相关问题