簡體   English   中英

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

供將來閱讀(如果您要求):我不是使用promises的專家,但是它的工作方式類似於AJAX請求。

當您向服務器發出請求( GETPOSTPUT等)時,您正在等待對此的響應(數據集合,消息,成功/失敗的POST / PUT / DELETE等)。 根據響應,您將對預期的事件進行編碼( errorsuccesscomplete等)。

在這種情況下,您正在使用axios ,這是一種處理AJAX請求的新方法。 error / success / complete / ...事件的等效方法是then()函數。 使用這種方法,您可以執行一些新任務或僅打印服務器的響應消息(對於您而言)。

MDN

then()方法返回一個Promise。 它最多包含兩個參數: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() });

我剛發現錯誤。 我在axios.post()中向PORT 333發出請求,但是服務器在端口3333上工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM