简体   繁体   中英

BrowserHistory in Node/Express with API

I am attempting to implement BrowserHistory for a React app that uses react-router. Based on the documentation , I have in my index.js :

let express = require('express');
let harp = require('harp');
let path = require('path');

let app = express();

app.use(express.static(__dirname + "/dist"));
app.use(harp.mount(__dirname + "/dist"));

// BrowserHistory code
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});

let port = process.env.PORT || 3333;
app.listen(port, () => console.log("Listening on port " + port) );

// ...
// Various app.get(...) endpoints below
// ...

However, this is now catching all API requests (for example, I want to make a GET request to /metric ) and returning index.html instead of the correct JSON data.

How do I implement BrowserHistory and have API endpoints?

You need to define app.get('*', ...) after app.get(...) for endpoints.

If you take a look at docs about "middleware" , you'll see that express app looks like a layered cake, every layer responsible for something. Each request pass throw all layers. Layer can execute some code, modify req , res and also can call for next() layer.

app.get('*', ...) handles all requests and doesn't call next() for, so if you define this before other middlewares, they won't be executed.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM