简体   繁体   中英

Dynamic routes fail to refresh in browser?

I have a react app using next-routes. Navigation works as expected but refreshing a page with a custom route 404s with Page does not exist .

This only happens with dynamic routes containing parameters.

routes.js:

const routes = require('next-routes')();

routes
  .add('/campaigns/new', '/campaigns/new')  //fine     
  .add('/campaigns/:address', '/campaigns/show') //fails
  .add('/campaigns/:address/requests', '/campaigns/requests/index') //fails
  .add('/campaigns/:address/requests/new', '/campaigns/requests/new'); //fails

module.exports = routes;

How can I configure the routes to allow refreshing custom routes?

As Canaan already mentioned, your server is not aware of the routes you created, and therefore throws a 404 error. You need to tell your server (not Next, but Express or http ) that there are dynamic routes at these locations. Check out the next-routes documentation to see how you can achieve that:

// server.js
const next = require('next')
const routes = require('./routes') // <- your routes file
const app = next({dev: process.env.NODE_ENV !== 'production'})
const handler = routes.getRequestHandler(app)

// With express
const express = require('express')
app.prepare().then(() => {
  express()
    .use(handler) // <- this line is important
    .listen(3000)
})

Refreshing routes in a browser or manually entering a url will cause the browser to make a network request to the url specified. Routes work within your app as the default function of the browser is prevented and the route in the address bar is updated to simulate how a typical non-spa web app would work. If you want this functionality then the right method would be to return your index.html file on all routes on your backend. If you do not have a backend then there are work arounds available for some static hosts. Here is a way to make routes work with github pages.

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