I'm using Node/Express as an API proxy server and want to know if it's possible to render HTML (index.html) page for all GET routes as well as expose API endpoints on the same port. I'm using client side routing (react-router).
For example:
// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
const html = renderHTML(req, res);
res.send(html)
});
// Expose API
app.all('/api/*', (req, res, next) => {
proxyRequest(...)
});
The problem is that doing when doing a GET request, the first app.get()
catches it (for example: fetch('/api/accounts')
).
I need to be able to make any request to any API endpoint route (besides /
) and have the client send any method (GET, PUT, POST...).
Can I serve index.html
to all client routes and have GET endpoints on the same port? Can I serve html to all routes except ones prefixed with /api/
?
If you expose your endpoints first and then serve your html, it should do the job.
// Expose API
api.all('/api/*', cb);
// Serve HTML
api.get('*', cb);
Make a directory called public
.
Put your HTML
and supporting files in it.
app.use(express.static(path.resolve('./public')));
//Your API routes here
The express.static
will serve the static HTML files and then you can add your route statements. This will work on the same port.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.