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
- Spotify player SDK in react
- Failed to start 'npm': Ensure that 'npm' is installed and can be found
- coding reactjs with the build in of html
- How to get 00:00; 10 September 2020 format from Date objects
- CORS Set Cookie Not working
- Effect hook for displaying initial data
- React with Google Apps Script
- Production mode styled components minification cause typeerror
- ReactJS error warning
- How to only allow a specific element type as children using Flow and React?
- how to use onClick when it renders
- How to check checkbox individually in a map array?
- How to extract single items from useQuery when accessing cache in another component?
- Dispatch redux action after Apollo Query component returns result
- Can i use npm link to attach React components?
- Should I use react-router for a tabs component?
- how to test props which is pass through Link in react router with React-testing-library or jest
- Loop through an array of nested objects in javascript
- How can i pass Actions info to Component, React + Redux?
- Material UI TablePagination handle with Redux/React
- Using svg-url-loader with Create React App
- Getting selected value in Material-UI Autocomplete
- React-table Select All Select Box
- Material ui InputBase can not be hided by other elements
- List items not staying in place using react-beautiful-dnd
- I should solve a React exercise of a timer and reset it by a button.I have problem with resetting my timer
- React Material UI Button component with hookrouter
- Creating a React Context with TypeScript to share state
- How do I resolve a Bad Request 400 error using send_mail function?
- How to dynamically route a user to a page depending the link clicked