React/Express应用程序只在根路由上加载,否则它会以JSON加载



我有一个React/Express应用程序,我使用React路由器。当我点击URL http://myapp.com时,React应用程序将毫无问题地加载,并且我将毫无问题地转到其他路由。如果我要直接访问任何其他路由,例如http://myapp.com/posts或http://myapp.com/login,就会出现这个问题——在那里,它会将组件将要使用的JSON数据加载到屏幕上。如果我访问myapp.com,然后切换到myapp.com/posts并点击刷新,它将加载JSON数据。

你知道我怎样才能让每条路由都发送静态文件吗?

这是我的。

我的结构如下:

client/
build/
node_modules/
public/
index.html
src/
components/
redux/
.gitignore
index.js
package.json
models/
node_modules/
public/
routes/
.env
.gitignore
package.json
server.js

Server.js:

require('dotenv').config()
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
const postsRouter = require('./routes/posts')
const commentsRouter = require('./routes/comments')
const usersRouter = require('./routes/users')
const path = require('path')
const session = require('express-session')
const passport = require('passport')
var cookieParser = require('cookie-parser')
const LocalStrategy = require('passport-local')
const mongoSanitize = require('express-mongo-sanitize')
const helmet = require('helmet')
const User = require('./models/user')
const PORT = process.env.PORT || 3001
const app = express()
app.set('views', path.join(__dirname, 'views'))
app.use(
helmet({
contentSecurityPolicy: false,
})
)
app.use(express.json())
app.use(
cors({
origin: herokuUrl,
credentials: true,
methods: ['GET', 'PUT', 'POST', 'OPTIONS', 'DELETE'],
})
)
app.use(express.static(path.join(__dirname, 'client', 'build')))
app.use(express.static(path.join(__dirname, 'public')))

app.use(cookieParser(process.env.COOKIE_SECRET))
app.use('/posts', postsRouter)
app.use('/posts/:id/comments', commentsRouter)
app.use('/', usersRouter)
app.all('*', (req, res) => {
res.status(404).json({ message: 'Invalid search term' })
})
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'))
})
app.listen(PORT, () => {
console.log(`listening on port ${PORT}`)
})

提前谢谢你

感谢您提供更多的信息。

看来你的问题是你在/posts,/login等处有反应路由,在同一位置也有API路由。

react-router-dom去到一个新的位置,它不会使另一个请求到您的服务器,因为它已经有它需要的所有文件(即你的index.js, css文件等),但当你刷新页面,你的浏览器正在使GET请求到该位置(例如/posts)。

您的快速服务器正在查看请求并以JSON响应。

你需要做的是确保你没有GET请求处理程序与你的路由具有相同的路径。

我的建议(虽然有很多其他的方法)是把你的API处理程序在/api。例如:/api/posts。然后,当你去到/posts的url时,它将从静态文件加载,但是当你向/api/posts发出GET请求时,express将知道提供JSON。

最新更新