【问题标题】:React button connection with database through axios.post()通过 axios.post() 反应按钮与数据库的连接
【发布时间】:2017-12-29 03:02:45
【问题描述】:

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

【问题讨论】:

  • 我很难理解你的问题。你有什么错误吗?
  • DerekHopper 是的,这就是错误:Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87)

标签: javascript sql node.js postgresql axios


【解决方案1】:

供将来阅读(如果您提出要求):我不是使用 promises 的专家,但它的工作方式类似于 AJAX 请求。

当您向服务器发出请求(GETPOSTPUT 等)时,您正在等待来自此的响应(数据集合、消息、成功/不成功 @ 987654328@/PUT/DELETE,等等)。根据响应,您将编写预期事件(errorsuccesscomplete 等)。

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

来自MDN

then() 方法返回一个 Promise。它最多需要两个参数: Promise 成功和失败情况的回调函数。

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

$.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() });

【讨论】:

    【解决方案2】:

    我刚刚发现了错误。我在我的 axios.post() 中向 PORT 333 发出请求,但服务器正在使用 3333 端口。

    【讨论】:

    • 我在想你想知道then() 是如何工作的
    • 嗯,是的,但是因为我不明白它是如何工作的,所以我认为我的应用程序因为 .then() 而无法工作。因此,如果有人解释了使用它的原因,我将不胜感激。
    • 检查我的答案。如果您觉得我的回答有用,请投票。如果您想要更多示例,请告诉我
    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 2019-05-09
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2019-07-16
    • 2017-06-14
    • 2012-06-05
    相关资源
    最近更新 更多