김기현
김기현

Reputation: 41

i have some problems about routing in node.js express

my app is SPA using react

I am trying to build API using express in node.js

so my server code is

const express = require('express');
const app = express();

const PORT = 80;
app.listen(PORT, () => {
    console.log('connected')
}}

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

//api
app.get('/user', .....
   res.json(~~~)
app.post('/user', .........
   res.json(~~~~)

Because my client is spa ( react ),

There is only one 'sendFile' in the server code.

all the rest is API, which returns JSON.

So I want to use API only about fetch or ajax ways

However, the current situation is that if client directly access the api url,

the browser can see json instead of my spa.

Is there a way to solve this problem?

thank you.

Upvotes: 0

Views: 51

Answers (1)

iofjuupasli
iofjuupasli

Reputation: 3873

To use SPA-way of routing, you need to separate urls of pages and api urls:

const express = require('express');
const app = express();

const PORT = 80;
app.listen(PORT, () => {
    console.log('connected')
}}

//api
app.get('/api/user', .....
   res.json(~~~)
app.post('/api/user', .........
   res.json(~~~~)

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

Notice that:

  1. /* route goes after api, so that all routes that don't match previous paths, render your SPA page
  2. You need to use * in SPA url pattern, so when you route to /user it renders SPA page, and then on client you render user page
  3. api prefix, that will differentiate your api and SPA paths

Upvotes: 1

Related Questions