Node.js 如何在相同的路径上为React和处理路由提供index.html服务?

Node.js 如何在相同的路径上为React和处理路由提供index.html服务?,node.js,reactjs,express,fastify,Node.js,Reactjs,Express,Fastify,使用react,如果用户没有第一次下载react_app.js,您需要在任何路径上提供包含react_app.js的index.html 然后您需要从react_app.js提供一些api调用,但是如果您使用相同的url作为GET,那么您将获得api调用响应,而不是react_app.js的index.html 解决这个问题的办法是什么?仅使用某些前缀进行api调用,并仅在未找到路由时发送index.html 我的代码: fastify.register(require('fastify-sta

使用react,如果用户没有第一次下载react_app.js,您需要在任何路径上提供包含react_app.js的index.html

然后您需要从react_app.js提供一些api调用,但是如果您使用相同的url作为GET,那么您将获得api调用响应,而不是react_app.js的index.html

解决这个问题的办法是什么?仅使用某些前缀进行api调用,并仅在未找到路由时发送index.html

我的代码:

fastify.register(require('fastify-static'), {
  root: path.join(__dirname, './static')
})

fastify.route({
  method: 'GET',
  url: '/',
  handler: async (req, res) => {
    res.send('you will get api call answer but you need to serve index.html with react_app.js first!!!!')
  }
})

正如@Garert所建议的,这就是它的工作方式:

// Статические файлы
fastify.register(require('fastify-static'), {
  root: path.join(__dirname, './static')
})

// this will work with fastify-static and send ./static/index.html
fastify.setNotFoundHandler((req, res) => {
  res.sendFile('index.html')
})

// Here go yours routes with prefix
fastify.register(async openRoutes => {
  openRoutes.register(require('./server/api/open'))
}, { prefix: '/api' })

正如@Garert所建议的,这就是它的工作方式:

// Статические файлы
fastify.register(require('fastify-static'), {
  root: path.join(__dirname, './static')
})

// this will work with fastify-static and send ./static/index.html
fastify.setNotFoundHandler((req, res) => {
  res.sendFile('index.html')
})

// Here go yours routes with prefix
fastify.register(async openRoutes => {
  openRoutes.register(require('./server/api/open'))
}, { prefix: '/api' })
您可以使用头在index.html和api调用之间切换,但我经常看到api调用位于/api/前缀处。这样更容易,因为有时设置标头不如使用不同的路由简单。您可以使用标头在index.html和api调用之间切换,但我经常看到api调用位于/api/前缀处。这样更容易,因为有时设置标题并不像使用不同的路由那么容易。