gpt4 book ai didi

javascript - 通过 axios.post() 与数据库 react 按钮连接

转载 作者:行者123 更新时间:2023-11-29 14:15:58 26 4
gpt4 key购买 nike

我有 4 个输入和按钮,它从中获取所有数据并通过 axios.post() 请求发送到我的 PostreSQL 数据库。不清楚 .then() 是如何工作的。所以,这是我的按钮代码,它只调用了 this.addNewPainting 函数:

<button onClick={ this.addNewPainting }>Submit</button>

这是我的 addNewPainting 函数:

addNewPainting() {
axios.post(`http://localhost:333/api/add`, {
title: this.state.titleInput,
year: this.state.yearInput,
size: this.state.yearInput,
location: this.state.locationInput
})
.then(function(response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}

在这个项目之前,我曾经使用 this.setState 将 response.data 放到数组中,但现在我有了数据库,我就卡住了。

这是我的 Controller 函数:

add_painting: (req, res, next) => {
const db = req.app.get('db');
const { title, year, size, location } = req.body;
console.log(title, year, size, location);

db.add_painting([ title, year, size, location ])
.then( () => res.status(200).send() )
.then( () => res.status(500).send() );
}

端点:

app.post('/api/add', paintings_controller.add_painting);

最佳答案

对于 future 的阅读(因为你要求它):我不是使用 promises 的专家,但它的工作方式类似于 AJAX 请求。

当您向服务器发出请求(GETPOSTPUT 等)时,您正在等待来自服务器的响应this(数据集合、消息、成功/不成功的 POST/PUT/DELETE 等)。根据响应,您将对预期事件(错误成功完成 等)进行编码。

在这种情况下,您使用的是 axios ,一种执行 AJAX 请求的新方法。 error/success/complete/... 事件的等效方法是 then() 函数。使用这种方法,您可以执行创建新任务的操作或简单地打印服务器的响应消息(在您的情况下)。

来自 MDN :

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

假设我们在 AJAX 中有这段代码:

$.ajax(
{
url : yourURL,
type : 'POST',
data : yourData,
datatype : 'json',
success : function(data) {
yourSuccessFunction(data);
},
error : function(jqXHR, textStatus, errorThrown) {
yourErrorFunction();
}
});

使用 axios,您将编写如下代码:

axios.post('/user', {
YourData: yourData
}).then(() => { this.yourSuccessFunction() })
}).catch(() => { this.yourErrorFunction() });

关于javascript - 通过 axios.post() 与数据库 react 按钮连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48000057/

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