The issue I am facing involves a 404 not found axios error when attempting to send a post request

I am attempting to send data via a post request from react.js to express.js using axios, but I keep encountering a 404 not found axios error. You can view the error image here.

Below is my code:

export default function Upload() {
   const [state, setState] = useState({
        title: "",
        desc: ""
    });
    const handleTextChange = (event) => {
        const value = event.target.value;
        setState({...state, [event.target.name]:value});
    }
   
     const handleSubmit = async e => {
        e.preventDefault();
        const Data= {
            title: state.title,
            desc: state.desc
        };
        axios
        .post("http://localhost:5000/uploadData", Data)
        .catch(console.log);
     }
     return(
        <div>
            <h1>Upload your video</h1>

            <Stack gap={2}>
                <Form onSubmit={handleSubmit}>
                    <Form.Group className="mb-3" controlId="formTitle">
                        <Form.Label>Title</Form.Label>
                        <Form.Control type="text" name="title" />
                    </Form.Group>
                    <Form.Group className="mb-3" controlId="formDesc">
                        <Form.Label>Description</Form.Label>
                        <Form.Control as="textarea" rows={3} name="desc"  onChange={handleTextChange} />
                    </Form.Group>
                    <Button variant="outline-primary" type="submit">submit</Button>
                    <Button variant="outline-light" type="reset">reset</Button>
                </Form>
            </Stack>
          </div>
    );
}

Express.js code on the server side:

const express = require("express");
const bodyParser = require('body-parser');
const router = express.Router();
onst app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

router.post("/uploadData", async (req, res) => {
  try{
    const newVideo = await Videos.create({title: req.body.title, desc: req.body.desc});
    res.send({newVideo});
  } catch(err) {
    res.status(400).send({error: err});

  }
});
const port = 5000;
app.listen(port, () => {
  console.log(`Server Listening on ${port}`);
});

Could someone please help identify the error in my code?

Answer №1

Your code has a few issues that need attention. First, it seems like you are not handling the response from your axios.post request. To fix this, update your code as follows:

axios.post("http://localhost:5000/uploadData", Data)
.then((response) => {
 // Handle response
 console.log(response.data);
})
.catch(error => {
   console.log(error)
})

Additionally, on the server-side, there is a typo in onst app = express();. Also, if you are not using a modular pattern and all your code is in the same file, you don't need the router. Instead, chain your HTTP methods directly to app. Make sure to mount the router using app.use() so that your app can respond to requests on /uploadData. Update your code like this:

const app = express(); //< Change 'onst' to 'const'
//...
//...
app.post("/uploadData", async (req, res) => { //< Change to app.post
  try{
    const newVideo = await Videos.create({title: req.body.title, desc: req.body.desc});
    res.status(201).json({  //< Send a json response with the newVideo
       newVideo
    });
  } catch(err) {
    res.status(400).json({  //< Send a json response with error
       error: err
    });
  }
});

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

Steps for assigning values to a JavaScript array using its indices

Question: Dynamically creating keys in javascript associative array Typically, we initialize an array like this: var ar = ['Hello', 'World']; To access its values, we use: alert(ar[0]); // Hello However, I am looking to assign ...

Having trouble passing AWS EMR Jupyter Notebook's socket through a node application. Unable to load kernel

We are facing an issue with our node application that serves as a proxy for the Jupyter notebook running on AWS EMR. While we can successfully proxy all HTTP requests using http-proxy-middleware, we are encountering difficulties when it comes to handling w ...

Is it possible to alter the name of a slot before displaying the element in the shadowDOM, depending on the slot utilized in the DOM?

In my project, I am working on implementing different features for both desktop and mobile devices. Some of these features can be replaced by slots. My goal is to have a slot that can be either replaced by a desktop slot called poster-foreground, or a mobi ...

Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

Generate an array using the properties of an object

Seeking a more efficient way to configure settings for an app using objects? Consider starting with the following object: var obj = { property_one: 3; property_two: 2; property_three: 1; } And transforming it into the desired array format: v ...

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

AngularJS UI-Grid not displaying JSON data

Just started learning AngularJS and everything was going smoothly until I hit a roadblock... I have been struggling to display the JSON data returned from my REST service call. While hard-coding a data array in my controller works fine, displaying the act ...

Nextjs encounters difficulty locating an internal API link

When attempting to fetch data from my internal API using an internal path, I encountered the following error: TypeError: Failed to parse URL from /api/hello** ------------ export async function getStaticProps() { const data = await fetch("/api/hello ...

What does the term "xs" signify in relation to Grid layout

Can you explain the significance of the xs in this code snippet? <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> < ...

Automatically load VueJS components based on the prefix of the tag

I am currently working on defining components based on the prefix when Vue parses the content (without using Vuex). While exploring, I came across Vue.config's isUnknownElement function but couldn't find any documentation about it. By utilizing ...

Reactjs: useEffect fails to trigger upon initial loading

Having trouble with useEffect not triggering at app load, but only on button click. Here's my code: export default function Person() { const [person, setPerson] = useState({}); const [hitRandomUser, setHitRandomUser] = useState(0); const fetchData = ...

What should we do to resolve the uncommon use of the 'this' es-lint error? Which rule should we disable?

Recently, I encountered an issue with my Nuxt setup that is configured with el-lint and prettier. Every time I try to use 'this' within my template, it throws up an error unexpectedly. 6:15 error Unexpected usage of 'this' vue/this ...

Comparing strings with if-else statement

I am having trouble comparing strings in this array. For some reason, the strings are never equal. var person = ["Sam", "John", "Mary", "Liz"]; var searchedName = prompt("Enter name"); var resultMessage = ""; for (index in person) { var currentName = ...

Creating a personalized input field with automatic spacing for entering a vehicle license plate number

Currently working on creating an input field for vehicle number entry, but facing an issue where pressing the backspace breaks the logic. Any help would be appreciated. https://i.stack.imgur.com/uTK6N.png React.useEffect(()=>{ if(cardNumber.length===2) ...

Are there any web browsers that automatically switch to a non-SSL connection if an attempt to connect with SSL

I regularly utilize jQuery along with jQuery.ajax to make connections between pages. I am interested in establishing a connection from a non-SSL page to an SSL page using ajax. Are there any web browsers that will attempt to connect via non-SSL if the con ...

Transferring a single JavaScript file to a different project directory in a Node.js environment

get(function (){ console.log(' Greetings, Earthlings'); }); I am struggling with accessing a JavaScript file located in a separate project folder within my Node Eclipse environment. I need to find a way to reference this file from my current ...

Struggling to unlock the mystery of a jammed trigger box

I'm currently working on implementing a small 'trigger box' that will expand upon clicking. It was functional before, but it seems to be encountering an issue now and I'm unsure of the cause. While I have some understanding of HTML and ...

Valums file-uploader: Restricting file uploads based on user's credit score

Currently utilizing the amazing file uploader by Valums, which can be found at https://github.com/valums/file-uploader One feature I am looking to incorporate is a limit based on the user's account balance. The initial image upload is free, so users ...

How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked. The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100" This is the current HTML ...

Exploring the bewilderment of retrieving values in a JavaScript

I'm confused about the return value of this code snippet: function foo() var ret = 0; var xhr=send_request( "bla", function() { // perform actions based on AJAX response // set the value of ret based on the response } ); return re ...