gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:11:31 26 4
gpt4 key购买 nike

我正在尝试从 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)
})
});
})

关于javascript - 如何使用 POST 路由从表单中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45450409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com