【问题标题】:Post form data axios in nodejs在nodejs中发布表单数据axios
【发布时间】:2020-12-29 02:34:29
【问题描述】:

我尝试使用 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.

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

【问题讨论】:

  • 这是 CORS 错误。您必须在服务器端后端授予权限。使用 cors 模块。如果您使用 express.js 作为后端,这很容易。
  • 这不是 cors 兄弟@ArtemMedianyk
  • 这是一个验证错误。如果正文中有消息,可以通过阅读正文中包含的错误消息尝试解决。但是 403 是权限错误。

标签: node.js axios multipartform-data


【解决方案1】:

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

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

类似:

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

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

它可能像 404 一样简单,您可能在其中输入的地址中有错字。

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

但无论哪种方式,如果您使用 catch 块正确处理承诺并控制台记录错误消息,您几乎肯定会看到更多信息。

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2017-06-05
    • 2018-12-25
    • 2021-02-16
    • 2021-05-24
    • 1970-01-01
    • 2020-09-24
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多