[英]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");
});
那應該有效,現在我想給你一些提示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.