Home > database >  Does node-fetch support request forwarding?
Does node-fetch support request forwarding?

Time:09-30

I'm trying to translate this code to work with node-fetch but I'm kinda stuck in figuring out how the node-fetch can forward the whole req bit since it's the one that contains the file I want to upload.

async function handler(req, res) {
  let uploadPhotoAddress = baseURL   "/upload";
  if (req.method == "POST") {
    const { data } = await axios.post(uploadPhotoAddress, req, {
      responseType: "stream",
      headers: {
        "Content-Type": req.headers["content-type"], // which is multipart/form-data with boundary included
        apikey,
      },
    });
    data.pipe(res);
  } else {
    return res.status(405).json({ message: "Method Not Allowed" });
  }
}

CodePudding user response:

I think it would look like this using node-fetch (with some additional error handling):

async function handler(req, res) {
    let uploadPhotoAddress = baseURL   "/upload";
    if (req.method == "POST") {
        try {
            const uploadResponse = await fetch(uploadPhotoAddress, {
                method: "POST",
                headers: {
                    "Content-Type": req.headers["content-type"],
                    apikey,
                }
                // the incoming stream is what we want to send
                //   to the upload server as the body
                body: req,
            });
            if (!uploadResponse.ok) {
                throw new Error(`unexpected response ${uploadResponse.statusText}`)
            }

            // send upload photo response back as result of original upload request
            uploadResponse.pipe(res);
        } catch (e) {
            console.log(e);
            res.status(500).json({ message: e.message });
        }
    } else {
        res.status(405).json({ message: "Method Not Allowed" });
    }
}

With node-fetch(), you can configure the body to be a readable stream (which is req in your code) and it will automatically read from that stream and send that data as the body of your POST.

Then, the result of await node-fetch(...) is likewise a readable stream that you can pipe as the response to the original incoming request.

  • Related