通过 axios.post() 反应按钮与数据库的连接

React button connection with database through axios.post()

我有 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放到数组中,但现在我有了数据库,我就卡住了。

这是我的控制器函数:

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

我刚发现错误。我在 axios.post() 中向端口 333 发出请求,但服务器正在端口 3333 上工作。

供日后阅读(因为您需要):我不是使用 promises 的专家,但它的工作原理与 AJAX 请求类似。

当您向服务器发出请求(GETPOSTPUT 等)时,您正在等待来自该服务器的响应(数据集合,一条消息,一条 succesful/unsuccesful POST/PUT/DELETE,等等)。根据响应,您将对预期事件(errorsuccesscomplete 等)进行编码。

在这种情况下,您使用的是 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() });