2021年3月10日星期三

React/Express application only loads on root route, otherwise it loads as JSON

I have a React/Express Application, and I'm using React Router. When I hit the URL http://myapp.com, the React app will load no problem, and I'll have no problem going to other routes. The issue occurs if I were to instead directly visit any other route, for example http://myapp.com/posts or http://myapp.com/login - there, it will load to the screen the JSON data that the component would have used. If I were to visit myapp.com and then nagivate to myapp.com/posts and hit the refresh, it will load the JSON data instead.

Any idea how I can get every route to send the static files for every route?

Here is what I have.

The structure I have is as follows:

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}`)  })  

Thank you in advance

https://stackoverflow.com/questions/66574580/react-express-application-only-loads-on-root-route-otherwise-it-loads-as-json March 11, 2021 at 07:55AM

没有评论:

发表评论