简体   繁体   English

动态路由无法在浏览器中刷新?

[英]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 . 导航按预期工作,但Page does not exist使用Page does not exist刷新具有自定义路线404s的Page does not exist

This only happens with dynamic routes containing parameters. 这仅在包含参数的动态路由中发生。

routes.js: route.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. 正如Canaan已经提到的那样,您的服务器不知道您创建的路由,因此会引发404错误。 You need to tell your server (not Next, but Express or http ) that there are dynamic routes at these locations. 您需要告诉服务器(不是Next,而是Express或http ),这些位置上有动态路由。 Check out the next-routes documentation to see how you can achieve that: 请查看next-routes文档,以了解如何实现:

// 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. 在浏览器中刷新路由或手动输入URL将导致浏览器向指定的URL发出网络请求。 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. 路由可在您的应用程序内工作,因为阻止了浏览器的默认功能,并且地址栏中的路由已更新,以模拟典型的非spa网络应用程序的工作方式。 If you want this functionality then the right method would be to return your index.html file on all routes on your backend. 如果您需要此功能,那么正确的方法将是在后端的所有路由上返回index.html文件。 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. 是使路由与github页面一起使用的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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