Encountering a 404 error when trying to reload the page?

My React Router is functioning properly in the development environment. Here's what I implemented in Webpack Dev Server:

historyApiFallback: {  
  index: 'index.html',
}

Now, when transitioning to production mode, I wanted to replicate the same behavior using Express. This is how I set it up:

const indexPath = path.join(__dirname, '../public/index.html')
const publicPath = express.static(path.join(__dirname, '../public'))

  app.use('/public', publicPath)
  app.use('/graphql', graphQLHTTP(async (req) => {
    let { user } = await getUser(req.headers.authorization); 
    if(!user) {
      user = 'guest'
    }
    return { 
      schema, 
      pretty: true,
      graphiql: true,
      context: {
        user,
      }
    }
  }); 

app.get('/', function (_, res) { res.sendFile(indexPath) });

I haven't made any changes to react-router-dom, so I suspect the issue lies within my Express configuration. What would be the equivalent of historyApiFallback in production mode? Below is a snippet from my webpack bundle configuration:

output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js',
    publicPath: '/public/'
  },

In my HTML file, I reference the bundle like this:

<script type="text/javascript" src="/public/bundle.js"></script>

Despite having what seems to be the correct configuration, I encounter a "cannot GET Error 404" upon reloading. Any insights on this issue?

Answer №1

Make sure to include the following line in your application:

app.get('*', function (_, res) { res.sendFile(indexPath) });

Alternatively, you could consider utilizing this package for better functionality: https://github.com/bripkens/connect-history-api-fallback

Take some time to learn more about the history mode:

To eliminate the hash from your URLs and provide a seamless navigation experience, utilize the router's history mode with the history.pushState API:

With history mode enabled, your URLs will appear clean and straightforward, like . Isn't that beautiful?

However, there is a potential issue to address: When users directly access a URL such as without proper server configuration, they may encounter a 404 error. That's not ideal.

No need to fret though! To resolve this, simply add a fallback route on your server that serves the index.html page when no static assets match the requested URL. Problem solved, yet again!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

Is there a way to access data from a different cart template containing personalized values on Shopify?

After analyzing the values required from product.json, I realized that the current method is not efficient. The client-side ends up processing unnecessary information and every new product or option adds to the request load. Below is the script responsible ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...

Is there a way to assign a specific color to individual users in a chat?

I have successfully implemented a chat feature using Pusher, but now I want to customize the appearance by changing the color of the username for the logged-in user when they are active in the conversation. Currently, both my username and another user&apos ...

Creating Angular Custom Form Validation and Custom Directives

I recently created a custom validation directive and applied it to the form element like this: <form myValidations> app.directive('myValidations', function(){ return{ //require: 'ngModel', note its commented out link: f ...

Having trouble getting the JavaScript function to run when clicking a button inside a div or form?

Hey there, so I've got this scenario where I have a button nestled within a div. Take a look at the HTML snippet below: <div class="row"> <button type="button" id="submit">Send</button> </div> Prior to this button, there ...

Adjust the styling with jQuery according to the selected value from the dropdown menu

Check out this Fiddle I have a jQuery script that is supposed to change the style of an input box to display:block if the selected value is "<>" (Between). However, currently it is changing the css for all selected items instead of just the target i ...

Scroll up event and sticky header using jQuery

I'm working on a function $(document).ready(function () { var lastScroll = 0; $(window).scroll(function(event){ var st = $(this).scrollTop(); if ((lastScroll - st) == 5) { $("header").css("position", "fixed"); ...

Exploring Next.js dynamic imports using object destructuring

import { UDFCompatibleDatafeed } from "./datafeeds/udf/src/udf-compatible-datafeed.js"; I'm facing a challenge in converting the above import to a dynamic import in Next.js. My attempt was as follows: const UDFCompatibleDatafeed = dynamic(( ...

Tips for modifying style.display using JavaScript

On my website, the menu is structured like this: <nav id="menu"> <label for="tm" id="toggle-menu">Menu <span class="drop-icon">▾</span></label> <input type="checkbo ...

Ensuring Sequential AJAX Calls in jQuery for Optimal Performance

I recently transitioned some code to FastCGI for backend processing of AJAX requests from a jQuery-driven front end. While FastCGI has generally sped up the process, I've encountered a performance drawback when two jQuery AJAX requests are made in rap ...

Nested loop combining Callback and Promise with two API requests

I apologize for the lackluster title, but I couldn't come up with anything more suitable. If this issue has already been addressed, please let me know in the comments and I will delete it promptly. However, keep in mind that this is a specific questio ...

Utilizing $index in AngularJS while iterating through ng-repeat items

Here is an example of an unordered list: <ul class="dropdown-menu inner" role="menu"> <li ng-repeat="availableAlphaName in availableAlphaNames" data-original-index="0" data-optgroup="1" class=""> <a tabindex="0" class="opt " st ...

Is there a way to determine which radio button has been chosen using jQuery?

I'm trying to retrieve the value of the selected radio button using jQuery. Can anyone help with this? Currently, I am able to target all radio buttons like so: $("form :radio") But how can I determine which one is actually selected? ...

One common issue popping up in Webpack logs is the error message "net::ERR_SSL_PROTOCOL_ERROR" caused by a call to sock

Using react on the front-end and .net core 3.1 on the back-end. Running webpack on localhost:8080 for client-side development. Configuring proxyToSpa in Startup.cs: applicationBuilder.UseSpa(spa => { spa.UseProxyTo ...

Sorting and Filtering JSON Data by Value in JavaScript: A Comprehensive Guide

After successfully integrating the Star Wars API to show character names from the "people" object in this JSON array retrieved from , I now need to filter the results based on a specific value which corresponds to . The current code displays all species of ...

Send the JSON file to the server by uploading it

Situation Currently, I'm dealing with a page comprising questions structured as shown below: sections:[{ section: 1, questions:[{ question: 1, attachment: [FormData Object] ... }, { question: 2, ...

Issue with jQuery sortable serialization when dynamically adding content is not being recognized

I've been attempting to re-order a list through ajax on sortable update. However, when I add a new item to the list via ajax after the sortable has already been initialized upon page load, it fails to recognize the new item with the "serialize" functi ...

Exploring the dynamic duo of Github and vue.js

As I am new to programming and currently learning JavaScript and Vue.js, I have been trying to deploy my first Vue.js app without success. Despite spending hours on it, I still cannot figure it out and need to seek assistance. Every time I try to deploy, ...

Retrieve Checkbox within a Span using Jquery

Trying to achieve the selection of a checkbox when a user clicks on a div using jQuery. The provided fiddle shows my attempt: http://jsfiddle.net/5PpsJ/ The code snippet I have written so far is as follows, but it doesn't seem to select the checkbox ...