Search code examples
javascriptreactjsexpressknex.js

How to retrieve data from form using a POST route?


I am trying to retrieve data from a Bootstrap form element, and save it to a PostgresSQL database using Express and Knex. There are no errors when I run the route; however, the data from the form is saved as null. Here is my form element (I'm using React):

render() {
  return (
    <form>
      <div className ="form-group">
        <label>Add a Note:</label>
        <textarea className="form-control" name="note" rows="5">
        </textarea>
      </div>
      <button onClick={this.handleClick} className="btn btn-primary" 
      type="submit">Submit</button>
    </form>
  )
}

Here is my fetch to the POST route:

handleClick(e) {
  e.preventDefault()
  fetch('/create-note', {
    method: 'POST'
  })
}

Here is my Express POST route (app.use(bodyParser.json()) is included in this file):

app.post('/create-note', (req, res) => {
  postNote(req.body.note)
    .then(() => {
      res.sendStatus(201)
    })
})

Here is the Knex postNote function:

export function postNote(newNote) {
  const query = knex
    .insert({ note_content: newNote })
    .into('notes')

  return query
}

Any help would be appreciated!


Solution

  • I found a solution and want to post it incase anyone else runs into a similar issue. The problem was I wasn't querying textarea's value correctly, so I was passing an undefined variable to the database to save. Here's the solution I came up with:

    handleSubmit(e) {
      const data = new FormData(e.target)
      const text = {note: data.get('note')}
      fetch('/create-note', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(text)
      })
    }
    
    render() {
      return (
        <form onSubmit={this.handleSubmit}>
          <div className ="form-group">
            <label>Add a Note:</label>
            <textarea className="form-control" name="note" rows="5">
            </textarea>
            <button ref="textarea" className="btn btn-primary" 
            type="submit">Submit</button>
          </div>
        </form>
      )
    }
    

    I put a onSubmit event listener on the form, and created a new FormData instance with the form. Then I created an object containing the value of the textarea to pass into the fetch call.