一些反应路线不适用于刷新或手动网址

时间:2020-02-20 10:33:00

标签: node.js reactjs express react-router-v4

我已经在StackOverflow或任何其他平台上阅读了所有可用的问题。我知道每次输入网址都会首先打到后端。但是,当后端和前端在不同的端口上工作时,这怎么可能呢?

这是我的服务器:

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

如果没有路由匹配,我确实有一个重定向到我的index.html的路由,但是当我输入一个url时,它永远不会到达后端路由。

使用邮递员也可以正常工作。前端react应用程序在端口3000上运行,后端在端口5000上运行。我没有收到任何错误,也没有页面刷新的错误。它不会加载它应该在前端的路由。

编辑:它到达路线但不呈现index.html页,我检查了目录,它应该可以正常工作,我不知道这是错的

1 个答案:

答案 0 :(得分:0)

此问题是因为react具有自己的服务器,默认情况下,将localhost @ 5000作为任何请求(代理)的前缀,因此您可以通过put解决它。

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

然后重新启动前端服务器多次,然后尝试您的请求。