Sending Data to Backend Using React Router and Express with an Ajax POST Request

I've encountered an issue while attempting to submit a basic form within a React component:

class UploadPartList extends Component {

  constructor(props) {
    super(props);
    this.state = { data: [] };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log('Submit button clicked');
    $.ajax({
      type: "POST",
      url: "/partListUpload",
      success: function(){
        console.log("Successfully posted");
      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    })
  }

  render() {
      return (
        <div>

          <form id="csvForm" action='' onSubmit={this.handleSubmit} method='post' encType="multipart/form-data">
            <p>upload your part number list (.xls or .csv)</p>
            <input id="uploadCSV" type="file" name="csv_form" />
            <input type="submit" className="submitButton" />
          </form>

        </div>
      );
  }
}

The configuration in my routes.js file is as follows:

import React from 'react';
import { Router, Route } from 'react-router';

import App from './components/App';

const Routes = (props) => (
  <Router {...props}>
    <Route path="/" component={App} />
  </Router>
);

export default Routes;

In my Express server, the routes are defined as shown below:

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});

app.use('/partListUpload', upload.single('csv_form'), partListUploadController);

app.post('/partListUpload', function(req, res) {
  res.send(req.body);
});

However, upon form submission, I encounter a 404 error. It appears that React is looking for the route specified by React Router rather than the one I've set up on the backend.

I have searched through various StackOverflow threads but haven't found a solution that resolves this issue. How can I reach a specific route on the backend?

Answer №1

My issue turned out to be that my Express server was not running properly. I utilized the create react app package to develop this application. Following a guide on integrating it with Express, I mistakenly kept trying to launch my app using 'npm start' in the CLI instead of 'npm run build' followed by 'node server/index.js'. Once I corrected this, everything started working smoothly.

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

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...

What is the best way to create a seamless Asynchronous loop?

Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List and Item (with a list containing items as well as additional associated data). For ins ...

Utilize Electron to extract and render content from a local file into HTML code

I am struggling to find a solution for automatically reading and parsing a local csv file in an electron application. When I use 'fs' to open the file, I can't figure out how to pass the contents into the HTML window. One option is to use a ...

Ensure that every route is prefixed with /api

Is there a way to set all routes accepted by Express to start with /api without explicitly defining it? Current: this.app.get('/api/endpoint-A', (req, res) => { return res.send('A'); }); this.app.get('/api/endpoint-B', ...

Testing a Jest unit on a function that invokes another function which in turn returns a Promise

I have a function that triggers another function which returns a Promise. Below is the code snippet for reference: export const func1 = ({ contentRef, onShareFile, t, trackOnShareFile, }) => e => { trackOnShareFile() try { func2(conte ...

minimize the size of the image within a popup window

I encountered an issue with the react-popup component I am using. When I add an image to the popup, it stretches to full width and length. How can I resize the image? export default () => ( <Popup trigger={<Button className="button" ...

Utilizing Spiderable within Meteor results in the replication of head content before it is presented in the body tags

Having trouble with my meteor site, thought it was Google indexing, now suspecting an issue with the Spiderable package. Meteor version 1.1.0.3 is in use, along with spiderable package and gadicohen:phantomjs as suggested by meteorpedia. The current issu ...

Every time I attempt to execute this piece of code in "node.js", an error pops up

const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const https = require('https'); const app = express(); app.use(express.static('public')); ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

Issues with the HTML required attribute not functioning properly are encountered within the form when it is

I am encountering an issue with my modal form. When I click the button that has onclick="regpatient()", the required field validation works, but in the console, it shows that the data was submitted via POST due to my onclick function. How can I resolve thi ...

Creating interactive lists on Android devices with PhoneGap and jQuery Mobile

I am facing an issue with my code. It works perfectly in Chrome, but when I try to run it on Android, the alert("test") function is never called. I created an apk using PhoneGap and am also using jQuery Mobile. Can anyone help me figure out what I am missi ...

Is there a way to automatically redirect the server URL when a file is modified?

I am currently experimenting with a function that is supposed to only display a message in the console without redirecting the actual URL of my server when a file is changed. watcher.add("/home/diegonode/Desktop/ExpressCart-master/routes/2.mk"); watche ...

All file upload requests consistently result in a status code of 400

I am encountering an issue with file uploading in Express. Every time I send a request with multipart/form-data, I receive a 400 bad request response with no error message, just an empty object. Currently, I am using busboy-body-parser for parsing multipar ...

Utilizing AJAX to showcase an HTML popup

I am currently working on a project to create an HTML page that will display another HTML file in an alert when a button is pressed. However, I am facing an issue where the content is not being displayed as expected. <html> <head> ...

Create a custom route variable in Node.js with Express framework

Is there a way to achieve this particular task using express.js? In my express.js application, I have set up a route like so: app.get('/hello', (req, res) => { // Code goes here }); This setup is functional, but I am curious if it is poss ...

The notify.js fails to display notifications in the event of an error

Why am I not receiving any error notifications even when there is an error message in the response object? $.ajax(settings).done(function (response) { if ( "error_message" in response ) { console.log(response); $.notify(" ...

Unlocking the contents of an array from a separate file in Next.js

I am developing a Quiz App that consists of two main pages: takeQuiz.js and result.js. My goal is to transfer the data from the multiple-choice questions (mcqs) in takeQuiz.js to be accessible in result.js. Utilizing router.replace(), I ensure that once th ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...