简体   繁体   中英

Some react routes don't work on refresh or manual url

I've read all the available questions here at StackOverflow or any other platform. I understand that every time a url is entered it first hits the backend. But how is that possible when backend and frontend work on different ports?

Here is my server:

app.use(cors())

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

connectDB()


const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () => console.log(`Server running on port ${PORT}`))



const socketio = require('socket.io')
const io = socketio(server)
const questions = require('./api/questions')(io)

app.use('/api/users', users)
app.use('/api/posts', posts)
app.use('/api/questions', questions)




express.static(path.resolve(__dirname, '/client/public'));

app.get('/*', (req, res) => {
    res.sendFile(__dirname + '/client/public/index.html'), err => console.log(err)
})

I do have a route that redirects to my index.html if no route is matched, however when I enter a url it never reaches the backend route.

It works fine using postman. Frontend react app runs on port 3000, backend runs on port 5000. I don't get any errors or what so ever on page refresh. It does'nt load the routes it should in the front end.

EDIT: it reaches the route but doesnt render the index.html page, I checked the directory,it should be working, i dont know wth is wrong

This problem because react has its own server and by default put the localhost@5000 as a prefix on any request (proxy) so you can solve it by put.

"proxy": "http://localhost@serverport"  // in the package.json file on the react

then restart your front server more than one time then try your requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM