Home > other >  Express function sending multiple times
Express function sending multiple times

Time:01-30

My react js file is currently like this

export default function Blog() {
    
    const [title, setTitle] = useState('');
    const [blog, setBlog] = useState('');
    const sumbitBlog = () => {
        axios.post('http://localhost:3001/api/insert', {
            title: title,
            blog: blog
            });
    }
    return (
        <div className='container'>
            <div className='row'>
                <form className='col-lg-12 form-group'>
                   <div className="form-group">
                        <label for="formGroupExampleInput">Title</label>
                        <input type="text" className="form-control"placeholder="Title" name="title" onChange={(e)=>{
                            setTitle(e);
                        }}/>
                    </div>
                    <div className="form-group">
                        <label for="formGroupExampleInput2">Body</label>
                        <input type="text" className="form-control" placeholder="Body" name="blog" onChange={(e) =>{
                            setBlog(e);
                        }}/>
                    </div>
                    <button className='btn-primary' type="submit"onClick={sumbitBlog()}>Submit</button>
                </form>
            </div>
            
        </div>
    );
}

And my nodejs back end code :

app.post('/api/insert', (req, res) =>{

    const title = req.body.title;
    const blog = req.body.blog;
    const sql = `INSERT INTO posts (title, body) VALUES ("this","works")`;
    db.query(sql,[title, blog], (err, result)=>{
        if(err) throw err;
        console.log(title);
        console.log(blog)
    });

});

even though it looks right, it keep sending multiple requests I have I don't know what is happening, I tried using different ways of doing it looking from the internet, but only this way it inserts to the database. any other way it wont even try connecting to it.

the database

CodePudding user response:

Try to pass a reference to the function instead of firing it every time you render it.

So: onClick={sumbitBlog} instead of: onClick={sumbitBlog()}

CodePudding user response:

Your backend function does not send a response back to the client, because it lacks a res.json() function call or similar. If you insert a statement

res.json(result);

after the two console.log statements, the client will receive a JSON response, which you must then use to somehow update the client so that the user can read that the insertion was successful. The following code simply alerts the user and displays the JSON, but you probably want something more elegant.

const sumbitBlog = async () => {
  var response = await axios.post('http://localhost:3001/api/insert', {
    title: title,
    blog: blog
  });
  alert(JSON.stringify(response.data));
}
  •  Tags:  
  • Related