簡體   English   中英

手動刷新或寫入時,React 路由器 URL 不起作用。 並獲取 html 數據而不是 JSON 數據

[英]React router URL don't work when refreshing or writing manually. and getting html data instead of JSON data

我正在使用 React-router 的 MERN 網站上工作,當我單擊鏈接按鈕時它工作正常,但是當我刷新我的網頁時,它沒有加載我想要的內容。 手動刷新或寫入時,React 路由器 URL 不起作用。 所以我看到了很多解決這個問題的方法。 我使用了一種解決方案,即捕獲 server.js 中的每個 get 請求並發送 index.html 文件。

if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client", "build")));

app.get("/*", function (req, res) {
    res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});

 }

這個過程完美地解決了反應路由器的問題,但在客戶端,我通過發送 Axios get 請求來獲取一些數據。

useEffect(() => {
          
        axios
            .get("/posts")
            .then((result) => {
                console.log(result.data);
      //result.data contains index.html file instead of json data
                
            })
            .catch((error) => {
                console.log(error);
            });
    }, []);

該 get 請求的響應應該具有 get JSON 數據,但它獲得了 index.html 文件。 我知道它會獲取那個 index.html 文件,因為我在捕獲 server.js 中的所有請求時發送了 index.html 文件。

app.get("/*", function (req, res) {
    res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});

但是如果我刪除那行代碼,那么在手動刷新或編寫 URL 時,我會遇到 React 路由器 URL 不起作用的錯誤。 我想要的是解決反應路由器問題,並從該請求中獲取 JSON 數據並使用該數據來映射這些數據。 這是我的 server.js、App.js 和 Posts.js 代碼

服務器.js

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
require("dotenv").config();
const path = require("path");

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

if (process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, "client", "build")));

    app.get("/*", function (req, res) {
        res.sendFile(path.join(__dirname, "client", "build", "index.html"));
    });
}
mongoose
    .connect(process.env.MONGODB_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        useFindAndModify: false,
    })
    .then(() => {
        console.log("Database connected");
    })
    .catch((err) => {
        console.log(`Database error ${err.message}`);
    });

const postsSchema = new mongoose.Schema({
    title: {
        type: String,
    },
    description: {
        type: String,
    },
});

const Posts = new mongoose.model("Posts", postsSchema);

app.get("/posts", (req, res) => {
    Posts.find({}, (error, post) => {
        if (error) {
            res.json(error.message);
        } else {
            res.json(post);
        }
    });
});


    
app.listen(process.env.PORT || 5000, () => {
    console.log("App started in port 5000");
});

應用程序.js

import "./App.css";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Posts from "./Posts";
import Header from "./Header";

function App() {
    return (
        <div className="App">
            <Router>
                <Header />
                <Switch>
                    
                    <Route exact path="/posts" component={Posts} />
                    
                </Switch>
            </Router>
        </div>
    );
}

export default App;

Posts.js

import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";

function Posts() {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
        axios
            .get("/posts")
            .then((result) => {
                setPosts(result.data);
                console.log(result.data);
               //result.data contains index.html file instead of JSON data
            })
            .catch((error) => {
                console.log(error);
            });
    }, []);

    return (
        <div className="container mt-5">
            <div className="row">
                {posts.map((post) => {
                    return (
                        <div className="col-sm-3" key={post._id}>
                            <h6>{post.title}</h6>
                            <p>{post.description}</p>

                            <Link className="nav-link active" to={`/post/${post._id}`}>
                                Read More
                            </Link>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}

export default Posts;

如果您知道我的代碼有什么問題,請幫助我。 以及如何獲取 JSON 數據而不是 index.html 文件

const express = require("express");
//const bodyParser = require("body-parser"); not necessary
const mongoose = require("mongoose");
require("dotenv").config();
const path = require("path");

const app = express();

//app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.urlencoded({ extended: false }));
//app.use(bodyParser.json());
app.use(express.json());

/*if (process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, "client", "build")));

    app.get("/*", function (req, res) {
        res.sendFile(path.join(__dirname, "client", "build", "index.html"));
    });
}*/
mongoose
    .connect(process.env.MONGODB_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        useFindAndModify: false,
    })
    .then(() => {
        console.log("Database connected");
    })
    .catch((err) => {
        console.log(`Database error ${err.message}`);
    });

const postsSchema = new mongoose.Schema({
    title: {
        type: String,
    },
    description: {
        type: String,
    },
});

const Posts = new mongoose.model("Posts", postsSchema);

// Static Files Folder
app.use(express.static(path.join(__dirname,"client","bluild")))

// Routes
app.use("/posts", (req, res)=>{
    Posts.find({}, (error, post) => {
        if (error) {
            res.json(error.message);
        } else {
            res.json(post);
        }
    });
})
app.use("/*", (req, res)=>{res.sendFile(path.join(__dirname,"public/index.html"))}) /*always at the end*/

app.listen(process.env.PORT || 5000, () => {
    console.log("App started in port 5000");
});

那應該有效,現在我想給你一些提示。

  • 最新版本中的 Express 包括 body-parser 如果您打算使用 1 個處理客戶端 + 服務器端的服務器(我的意思是不使用 create-react-app 並創建其他服務器來發出請求):
  • 拳頭,您必須清除靜態文件夾,您將在其中放置用 react 制作的包(在您的情況下,我認為它是 index.js)。
  • 沒有必要為不存在的路由重新發送包,您可以向客戶端發送一個 json (res.json({Status: 'NotFound'})) 並且您必須在那里顯示用戶該頁面不存在(使用反應,創建一個組件 NotFound 並確保它是路由中的最后一個路由)或只發送 res.status(401)。 但是,如果您使用下一點,這不是必需的。
  • 在 react-router 中,你應該使用“HashRouter as Router”而不是“BrowserRouter as Router”,解釋起來有點困難,你可以找到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM