Reputation: 41
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
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:
/*
route goes after api, so that all routes that don't match previous paths, render your SPA page*
in SPA url pattern, so when you route to /user
it renders SPA page, and then on client you render user
pageapi
prefix, that will differentiate your api and SPA pathsUpvotes: 1