How to get data from a form using the POST route?

I am trying to extract data from a Bootstrap form element and save it in a PostgresSQL database using Express and Knex. There are no errors when starting the route. however, data from the form is saved as null. Here is my form element (I use 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 choice for the POST route:

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

Here is my POST express 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!

+4
source share
3 answers

, - . , textarea , undefined . , :

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>
  )
}

onSubmit FormData . , textarea, .

0

POST , , , .

app.post('/create-note', (req, res) => {
    var body = '';
    request.on('data',function(data) { body += data; });
    request.on('end', function(data) {
        postNote(body)
            .then(() => {
                res.sendStatus(201)
            })
    });
})
+1

fetch

...
<form method="POST" action="/create-note" enctype='application/json'>
    ...
</form>
...

application/x-www-form-encoded (doc), -.

...
app.use(bodyParser.urlencoded({ extended: true }));
...

...

...
<button ref="form" onClick={this.handleClick} className="btn btn-primary" 
      type="submit">Submit</button>
...

handleClick(e) {
  e.preventDefault();
  const data = new FormData(this.refs.form);

  fetch('/create-note', {
    method: 'POST',
    body: data
  })

}
+1

Source: https://habr.com/ru/post/1682810/


All Articles