【问题标题】:The \"path\" argument must be of type string or an instance of Buffer or URL. Received undefined from nodejs\"path\" 参数必须是字符串类型或 Buffer 或 URL 的实例。从 nodejs 收到 undefined
【发布时间】:2021-08-18 16:16:53
【问题描述】:

我正在尝试从 reactjs 获取文件并作为参数发送到 Node.js 后端以在 API 中进行处理。但它给了我这个错误。代码如下:

const FormData = require("form-data");
    const fs = require("fs");
    const model = "tr-8";
    const formd = new FormData();
    const { voice } = req.body;
    const file = voice;
    const timeout = 360000;
    formd.append("model", model);
    formd.append("files[]", fs.createReadStream(voice, { autoClose: true }));
    const request = formd.submit(
      `${Process.env.API}` + model,
      function (err, rs) {
        if (err) {
          console.log("formd.submit error " + voice);

          console.log(err);
        }

        if (rs) {
          var resp = Buffer.from([]);

          rs.on("error", function (err) {
            console.log("formd.submit on error " + voice);

            console.log(err);
          });

          rs.on("close", function () {
            console.log("close " + voice);
          });

          rs.on("data", function (chunk) {
            resp = Buffer.concat([resp, chunk]);
          });

          rs.on("end", function () {
            console.log("end " + voice);

            const resputf8 = resp.toString("utf8");

            const recognitionResult = JSON.parse(resputf8);

            const speech = recognitionResult.JsonResult;

            if (speech.error) {
              console.log("transcript error " + speech.error + " " + voice);
            } else {
              console.log(JSON.stringify(speech, null, 2));
            }
          });
        }
      }
    );

而在前端,我会这样发送文件:

<Input type="file" name="voice" />

这是我的错误代码:

    at ReadStream._construct (node:internal/fs/streams:64:17)
    at constructNT (node:internal/streams/destroy:288:25)
    at processTicksAndRejections (node:internal/process/task_queues:80:21) {
  code: 'ERR_INVALID_ARG_TYPE'

我怎样才能防止这个错误?

【问题讨论】:

  • 能否在问题代码中添加错误堆栈详情?
  • @ApoorvaChikara 我添加了错误代码
  • 问题出在const { voice } = req.body; 错误来自语音未定义。你在使用 bodyparser 和 multer 吗?
  • @Mehrdad 我不使用 bodyParser 因为它已被弃用
  • @nilufer17 express.urlencoded 然后。记录声音,是否已定义?

标签: javascript node.js reactjs file


【解决方案1】:

您需要 multer 来处理多部分文件和上传。在前端添加这个

<form action="/voice" method="post" enctype="multipart/form-data">
  <input type="file" name="voice" />
</form>

在后端,

var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

app.post('/voice', upload.single('voice'), function (req, res, next) {
    // req.file is the `voice` file
    const  voice  = req.file
    // req.body will hold the text fields, if there were any
})

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2021-06-10
    • 2021-06-24
    • 2021-08-07
    • 2022-01-21
    • 2021-12-07
    • 2022-07-13
    • 2022-11-11
    • 2021-03-16
    相关资源
    最近更新 更多