简体   繁体   中英

React and Dynamic Routes including Filename and Extension

I am new to React and trying to put a CMS driven application together as kind of a POC. I am majorly stuck on how to get a full URL (including filename and ext) into a dynamic route in a React application. For example if I call this

http://localhost:8080/en/us/fly/index

The dynamic route picks it up. But if I call this

http://localhost:8080/en/us/fly/index.html

I get the following error. Cannot GET /en/us/fly/index.html

It is a requirement that I handle all URLs through my route even if they have a file extension & filename. My routes.jsx is as follows:

import React from 'react';
import {
  Switch, Route
} from 'react-router-dom';

// Pages
import Page from "./pages/Page";

class Routes extends React.Component {
  render() {

    return (
      <Switch>
        <Route path="/:page" component={Page} />
      </Switch>
    )
  }
}

export default Routes;

and my server.js is as follows:

const path = require('path')
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

// get an instance of router
const router = express.Router();

// serve static assets normally
router.use(express.static(__dirname + '/dist'))

router.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
})

// apply the routes to our application
app.use('/', router);

app.listen(port);
console.log('Site available on port ' + port);

How can I get all URLs to pass through my dynamic route? Is this even possible? I need to know if there are limitations in React that prevent this vs how it would work in a traditional ASP.Net MVC application where I can do this kind of dynamic routing.

Any help or advice on this will be very much appreciated as I am very stuck with this and don't fully understand the React world enough to find the solution.

Thanks in advance,

You can use *.* in your route. It matches with file extensions as below

<Route path="*.*" component={YOUR_COMPONENT}/> // matches /hello.jpg and /hello.html

Then you can access the props in your component as

// CMS name: sample.html
this.props.params.splat[0] // For name of prop without extension. It Will give 'sample'
this.props.params.splat[1] // For extension itself. It will give 'html'

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