React 路由与 Express 路由发生冲突。

huangapple go评论76阅读模式
英文:

React routes gets conflicted with express routes

问题

问题是当您访问 http://localhost:5000/api/users 时,您从您的React应用程序收到了404未找到错误。要解决这个问题,您需要确保以下几点:

  1. Express路由配置:确保您的Express应用程序在处理 http://localhost:5000/api/users 请求时正确配置路由。您已经有一个路由处理 /api/users,但是它仅返回一个JSON响应,这是正确的。但是,如果您想在浏览器中访问此URL并在React应用程序中渲染页面,您需要创建一个用于渲染React页面的路由。

  2. React Router配置:在React应用程序中,确保您正确配置了React Router,以便它可以处理 http://localhost:5000/api/users 请求并渲染相应的组件。您的React Router配置看起来已经处理了根路径 //login/register,但如果您想处理 /api/users,您需要添加一个适当的Route。

如果您需要更详细的指导,请提供您的Express和React Router配置,以便我可以为您提供更具体的帮助。

英文:

I have the build files (from npm run build) of the react application in the /public folder on my backend folder.

This is what is in my index.js on my backend

const express = require('express')
const mysql = require('mysql');

const path = require('path')

const app = express()
app.use(express.static(path.join(__dirname + "/public")))
app.use(express.json())

const PORT = 5000
app.listen(PORT)


app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, '/public/index.html'), function(err) {
        if (err) {
            res.status(500).send(err)
        }
    })
})

const db = mysql.createConnection({
    user: "root",
    host: "localhost",
    password: "",
    database: "project_db",
});

const users =
[
    { id: 1,name: "Andrew" },
    { id: 2, name: "Steve" },
    { id: 3, name: "John" },
    { id: 4, name: "Michael" },
    { id: 5, name: "Christian"  }
];

app.get("/api/users", (req, res) => {
    res.json(users);
})

app.post("/api/register", (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const email = req.body.email;
    
    db.query("INSERT INTO users (name, password, email) VALUES (?, ?, ?)", [username, password, email]);

    res.send({
        "message": "account registered",
        "status": 1,
    });
});

App.js on my react app

import { Route, Routes } from 'react-router-dom'
import './components/App.css'
import Home from './pages/Home'
import Login from './pages/Login'
import Register from './pages/Register'

function App() {
    return (
        <>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/login" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="*" element={ <h1>Not found (404)</h1> } />
            </Routes>
        </>
    );
}

export default App;

My question: When I go to http://localhost:5000/api/users it gets the 404 not found from my react app

How can I fix this problem?

答案1

得分: 1

以下是您要翻译的部分:

List your backend API endpoints before the "*" "endpoint" that returns the React app.

// Backend APIs
app.get("/api/users", (req, res) => {
res.json(users);
})

app.post("/api/register", (req, res) => {
const username = req.body.username;
const password = req.body.password;
const email = req.body.email;

db.query("INSERT INTO users (name, password, email) VALUES (?, ?, ?)", [username, password, email]);

res.send({
"message": "account registered",
"status": 1,
});
});

// Frontend React app routes
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, '/public/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
});

英文:

List your backend API endpoints before the "*" "endpoint" that returns the React app.

const express = require('express');

...

// Backend APIs
app.get("/api/users", (req, res) => {
  res.json(users);
})

app.post("/api/register", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const email = req.body.email;
    
  db.query("INSERT INTO users (name, password, email) VALUES (?, ?, ?)", [username, password, email]);

  res.send({
    "message": "account registered",
    "status": 1,
  });
});

// Frontend React app routes
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
});

huangapple
  • 本文由 发表于 2023年1月5日 01:42:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75009269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定