简体   繁体   中英

API resolved without response during file upload in Next.js

Although my code works fine, the console throws the following warning:

API resolved without sending a response for /api/image-upload

The endpoint itself uploads an image to Digital Ocean's object storage service "Spaces", and sends back some metadata (like the location):

import formidable from "formidable-serverless";
import aws from "aws-sdk";
import fs from "fs";

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async (req, res) => {
  const s3 = new aws.S3({
    endpoint: "...",
    accessKey: "...",
    secretKey: "...",
  });

  const form = new formidable.IncomingForm();

  form.parse(req, async (err, fields, files) => {
    if (err) return res.status(500);

    const path = files["file[]"].path;
    const file = fs.readFileSync(path);
    const name = files["file[]"].name;

    s3.upload({
      Bucket: "my-bucket",
      ACL: "public-read",
      Key: `${...}/${name}`,
      Body: file,
    }).send((err, data) => {
      if (err) return res.status(500);
      fs.unlinkSync(path);

      res.json({
        file: {
          url: data.Location,
        },
      });
    });
  });
};

You can avoid this warning by disabling the warning for unresolved requests.

/api/image-upload

export const config = {
  api: {
    externalResolver: true,
  }, 
}

Custom config

Or wrap form.parse into a promise:

const formFields = await new Promise(function (resolve, reject) {
    form.parse(req, (err, fields, files) => {
        if (err) {
            reject(err);
            return;
        }
        resolve({fields, files});
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM