首页 > 解决方案 > 在nodejs中发布表单数据axios

问题描述

我尝试使用 Axios 发布表单数据。

这是我的代码

const mydata = new FormData();
mydata.append("id", "4d2f9262-e578-4290-97d3-43303fffbf56");
mydata.append("filter", 2);

axios
  .post("https://www.lalal.ai/api/preview/", mydata, {
    headers: { "Content-Type": "multipart/form-data" },
  })
  .then((res) => {
    console.log(res);
  });

但我收到这样的错误

(node:54756) UnhandledPromiseRejectionWarning: Error: Request failed with status code 403
    at createError (D:\reactjs\upload_lalal\server\node_modules\axios\lib\core\createError.js:16:15)
    at settle (D:\reactjs\upload_lalal\server\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (D:\reactjs\upload_lalal\server\node_modules\axios\lib\adapters\http.js:244:11)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:54756) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:54756) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

有人可以向我解释为什么这是错误以及如何解决吗?

标签: node.jsaxiosmultipartform-data

解决方案


在你的 promise 结构中添加一个 catch 块。这不是根本问题,但在 Promise 管道中丢失的错误信息将对您的故障排除工作非常有价值。

即使您只是记录错误消息,您也会对正在发生的事情有更多了解。

就像是:

// You already have this...
.then((res) => {
  console.log(res);
})
// Add this part
.catch((e) => {
  console.log(e)
});

您当前看到的错误是让您知道您需要在 Promise 结构中处理错误响应。

它可能像 404 一样简单,您可能在您所寻找的地址中有拼写错误。

更新编辑 我注意到在未处理的承诺拒绝消息中,它显示错误 403。我不记得在这种情况下这是在后台发生的某种自动业务,还是您实际上收到了来自该站点的禁止响应您正在尝试访问。

但无论哪种方式,如果您使用 catch 块和 console.log 正确处理错误消息,您几乎肯定会看到更多信息。


推荐阅读