简体   繁体   中英

How can I post data from react to sql database

When I try to post data it gives me GET http://localhost:5000/stored 404 (Not Found) . How can I post data and then store it in mysql database?

This is code in React

import React from 'react'
    class InsertProduct extends React.Component{
        constructor(){
            super( )
        }

   postData(){

    fetch('/stored', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            },
        body: JSON.stringify({
            firstParam: 'yourValue',
            secondParam: 'yourOtherValue',
        })
        })

   }
    render(){
        return(
            <div>
                <button onClick={() => this.postData()}>Submit</button>
            </div>
        )
    }
}


export default InsertProduct;

And this is node and express

app.post('/stored', (req, res) => {
  res.send(req.body)

});

You would have to share some more of your code in order for me to know exactly what is wrong. But the error says it can't locate a GET method on the "/stored" endpoint on port 5000.

  • You are sharing code for a POST endpoint, but your error message says GET. So something is weird there. You should double-check that that error message is occurring due to the post request.
  • In your react code you just have fetch("/stored"...), is 5000 the correct port that your server is listening on?
  • Another possible issue is maybe you have a bug in some express middleware code you didn't share.

For debugging, start by just logging a response from the endpoint:

 app.post('/stored', (req, res) => { res.send('POST request received'); })

Once you confirm you're getting that response as expected then move on to parsing the body of the req and sending it to your database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM