【问题标题】:Angular 7 HttpClient: ToPromise does not work with put requestAngular 7 HttpClient:ToPromise 不适用于 put 请求
【发布时间】:2019-07-03 17:59:43
【问题描述】:

我正在尝试使用 express 创建一个 HTTP put 请求 API,该 API 在竞争时调用一个函数。我成功获得了更新数据库的 API 调用,但没有调用 .then() 和 .catch() 中的函数。 toPromise() 对 put 请求不起作用吗?

在前端,我尝试向函数添加类型并将其定义为异步。在后端,我尝试重组 .then() 和 catch() 语句。似乎没有任何效果。

app.component.ts

public async save(): Promise<any> {
    return this.httpClient.put<any>('/api/update-account', {
      name: this.name,
      email: this.email
    }).toPromise()
      .then(() => {
        // Run if successful put request
        success()
      })
      .catch(() => {
        // Run if error
        fallback()
  })
}

server.js

app.put('/api/update-account', (req, res) => {
    let name = req.body.name;
    let email = req.body.email;

    sql.connect(dbConfig).then(() => {
        return sql.query`UPDATE users SET Name=${name} WHERE Email=${email}`
        .then(result => {
            console.log(result);
            sql.close();
        }).catch(err => {
            console.log(err);
            sql.close();
        })
    }).catch(err => {
        console.log(err);
        sql.close();
    })
});

我希望 success() 或 fallback() 在 API 请求之后运行,但都没有被调用。

【问题讨论】:

  • 你不会在你的 put 中发回响应,至少在可见代码中是这样。所以 then 可能永远不会触发。尝试从 put 代码中至少发送 200。

标签: node.js angular express node-modules put


【解决方案1】:

您需要使用 express 返回响应。例如:

return res.status(200).send('My value');

因为您没有在任何地方返回响应,所以不会向客户端返回任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多