softcode
softcode

Reputation: 4648

Serving SPA from API server

From what I understand, the de facto method of serving an SPA is by implementing a catch all method for GET requests. So what happens if I both host the API and serve the SPA from the same server, and need to retrieve a resource e.g. /users?

How do you handle routing API calls/resources in a setup where your API server is serving your SPA?

e.g. using express:

import express from 'express'
import path from 'path'

const app = express()
const port = 3000

app.use(express.static(path.resolve(__dirname, '../client/dist')));


// Conflict here  <---------------------
app.get('/users', (req,res) => {
  // respond with users 
})

// And here       <---------------------
app.all('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../client/dist', 'index.html'));
})

app.listen(process.env.PORT || port, () => {
  console.log(`App listening on ${process.env.PORT || port}`)
})

Intuition tells me to implement a catch all for GET requests for the SPA while implementing an exception to the /api resource for API calls. But then there's the problem of accessing the /api through the browser.

Any ideas greatly appreciated.

Upvotes: 0

Views: 590

Answers (1)

Fan Jin
Fan Jin

Reputation: 2460

Add good idea would be adding api prefix to your rest API endpoints. Like /api/users for your user api.

Upvotes: 1

Related Questions