3

Using react you need to serve index.html with react_app.js included in it at any route if user have not downloaded react_app.js (came first time).

Then you need to serve some api calls from react_app.js, but if you use same url for GET, let's say, you will get API call response and not the index.html with react_app.js.

What is the solution for this? Make api calls only with some prefix and send index.html only if route not found?

My code:

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!!!!')
  }
})
1
  • 1
    You can use the Accept header to switch between the index.html and the api calls, but most often I see api calls at a /api/ prefix. It's easier that way, because sometimes setting the header is not as easy as just using a different route. Commented Feb 8, 2019 at 18:29

1 Answer 1

10

As @Garrert suggested, this is how it will work:

// Статические файлы
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' })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.