无法连接react到后端node js服务器express

问题描述 投票:0回答:2

我是初学者,我正在尝试了解 PORT 和服务器端与 React js 的连接。 我一直在阅读一篇文章并尝试将 React JS 连接到 Node 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"
  }
}
javascript node.js reactjs express
2个回答
1
投票

根据聊天讨论,以下是问题的解决方案

首先,您需要在服务器端代码中定义一个端点,如下所示:

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
端点,它应该可以正常工作。请确保服务器已启动并正在运行。

参考链接 - 使用节点后端创建 React 应用程序


0
投票

连接react到后端nodejs服务器express

您可以在package.json中定义

proxy

//  client/package.json
{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "proxy": "http://localhost:3000" //  Backend port
  "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"
  }
}

如果您使用Vite,那么您必须在

vite.config.js

中进行更改
export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
             // this generate: '/api/your-endpoint' => '/your-endpoint'
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },


    }
  }
})

查看 Vite 文档 server.proxy

© www.soinside.com 2019 - 2024. All rights reserved.