如何使用 POST 路由从表单中检索数据?

How to retrieve data from form using a POST route?

我正在尝试从 Bootstrap 表单元素中检索数据,并使用 Express 和 Knex 将其保存到 PostgresSQL 数据库中。我运行路由时没有错误;但是,表单中的数据保存为空。这是我的表单元素(我使用的是 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>
  )
}

这是我对 POST 路线的抓取:

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

这是我的 Express POST 路线(app.use(bodyParser.json()) 包含在此文件中):

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

这是 Knex postNote 函数:

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

  return query
}

如有任何帮助,我们将不胜感激!

对于 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)
            })
    });
})

在您的标记中尝试以下内容,并放弃使用 fetch

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

或者由于表单的默认编码是 application/x-www-form-encoded (doc),请将以下中间件添加到您的 Express 应用中..

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

}

我找到了解决方案并想 post 以防其他人遇到类似问题。问题是我没有正确查询 textarea 的值,所以我将一个未定义的变量传递给数据库进行保存。 这是我想出的解决方案:

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 实例。然后我创建了一个对象,其中包含要传递到 fetch 调用中的 textarea 的值。