score:285
i'm assuming you're using webpack. if so, adding a few things to your webpack config should solve the issue. specifically, output.publicpath = '/'
and devserver.historyapifallback = true
. here's an example webpack config below which uses both of ^ and fixes the refresh issue for me. if you're curious "why", this will help.
var path = require('path');
var htmlwebpackplugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicpath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devserver: {
historyapifallback: true,
},
plugins: [
new htmlwebpackplugin({
template: 'app/index.html'
})
]
};
i wrote more about this here - fixing the "cannot get /url" error on refresh with react router (or how client side routers work)
score:0
adding to the accepted answer, if you are using the htmlwebpackplugin
and still getting errors double check the filename
property. if you are setting the filename
specifically for production then you will need to add a condition to set the filename
contingent on the webpack_dev_server
variable. please see the example below:
new htmlwebpackplugin({
template: './src/index.html',
filename: process.env.webpack_dev_server ? 'index.html' : prod_html_path,
})
score:1
if you use webpack check your configuration in part of server configuration for the "contentbase" attribute. you can set by this example:
devserver: {
...
contentbase: path.join(__dirname, '../')
...
}
score:2
i also had success with this by adding ... historyapifallback: true
devserver: {
contentbase: path.join(__dirname, "public"),
watchcontentbase: true,
publicpath: "/dist/",
historyapifallback: true
}
score:3
i was having the same issue, what fixed it for me was editing my package.json
file, and under scripts: {
"build": "webpack -d && copy src\\index.html dist\\index.html /y && webpack-dev-server --content-base src --inline --port 3000"
at the end of my webpack build
code i added --history-api-fallback
this also seemed like the easiest solution to the cannot get /url
error
note: the next time you build after adding --history-api-fallback
you will notice a line in the output that looks like this (with whatever your index file is):
404s will fallback to /index.html
score:3
if you are using express (not webpack), this worked for me..
app.get('/*', function(req, res) {
res.sendfile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
score:8
if your application is hosted on a static file server, you need to use a instead of a .
import { hashrouter } from 'react-router-dom'
reactdom.render((
<hashrouter>
<app />
</hashrouter>
), holder)
score:10
it worked for me just need just addding devserver { historyapifallback: true }
is ok, not need use publicpath: '/'
usage like:
devserver: {
historyapifallback: true
},
score:16
just to supplement tyler's answer for anyone still struggling with this:
adding the devserver.historyapifallback: true
to my webpack config (without setting publicpath
) fixed the 404/cannot-get errors i was seeing on refresh/back/forward, but only for a single level of nested route. in other words, "/" and "/topics" started working fine but anything beyond that (e.g. "/topics/whatever") still threw a 404 on refresh/etc.
just came across the accepted answer here: unexpected token < error in react router component and it provided the last missing piece for me. adding the leading /
to the bundle script src in my index.html
has solved the issue completely.
Source: stackoverflow.com
Related Query
- React Router Error - Cannot GET [Page Name]
- React Router Cannot Get / depending on onEnter function
- get parameter value from url using React Router
- how get react router origin url without params?
- react router 4 and express : cannot GET
- React Router v6 Route element cannot get Context value
- React router v4 history, is there a way to get the url you are navigating from?
- Cannot get / with React Router
- Get router value from url in react
- How to get the last part of the current URL with react router v6?
- Cannot get props to pass through variable path /:id, react router dom
- How to get URL parameter from a React Router path
- React installed react router but cannot get the page to render
- React Router V4 - Can't get URL params in props
- React Router cannot GET /route only after deployed to Heroku
- react router gives a url with a pad sign and a get parameter
- Get React Router URL
- Fix cannot GET /url react router
- React router cannot route url with search string
- React Router - get URL params outside of page component (inside of layout footer)
- react router Cannot GET
- React Router not working Cannot GET /about
- React Router v4 - How to get current route?
- react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined
- React router changes url but not view
- Cannot read property 'history' of undefined (useHistory hook of React Router 5)
- Root Navlink always get active class React Router Dom
- React router - Update URL hash without re-rendering page
- react router get full current path name
- How to get params in component in react router dom v4?
More Query from same tag
- React self-modifying component with proper state/props
- react cookie consent not registering on first site visit
- React Search - I'm trying to create a filter and it doesn't work
- How to dynamically create a React component based on url param?
- React page is not redirecting
- this.state not the same as state in this object
- Displaying JSON multi-dimensional array data with ReactJS and map
- Using nested objects in redux initial state and reducers
- React: [name] is not detected
- React Antd DatePicker with custom format for input and for display
- Dynamically create functions in React to be consumed for react-router-dom
- Extending component event handler props in React
- How to trigger update in React using Effect hook
- Redux toolkit. Uncaught Error: uSES not initialized
- React dangerouslySetInnerHTML and iframes
- Access object nested in React object prop
- React, Immutable, fetch() - incorrect error handling leading to undefined state element?
- D3 Radial Dendrogram jumps to top left
- Vertically centring a div containing two text areas
- How to pass data between Gatsby Markdown pages in a React JS app
- Get URL pathname in nextjs
- setState after loading an array from firebase
- Better way to add types to props in a functional component in NextJS Typescript project
- Cannot pass mongo/express data to react
- React:Can't perform a React state update on an unmounted component?
- react TypeError: Cannot read property 'id' of undefined
- Angular 6: continuously execute http request inside ngAfterContentChecked after receive data from parent component
- Material UI Autocomplete: exclude defaults from options
- Should Custom React Hooks Cause Re-Renders of Dependent Components?
- How to transfer data from react child component to parent component