Search code examples
requesthttphandlerdenofreshjs

Handle the payload of a POST request from Node-RED with deno fresh framework


When I sent a POST request to an endpoint with node-red I can't find a way to access the data that I sent in msg.payload with the POST handler that I made with deno fresh.

I tried to get the data from the req.body but it returns:

ReadableStream { locked: false }

so I printed the hole request of the handler and the data aren't anywhere in the request.

The handler code is the following:

import { Handlers, HandlerContext } from "$fresh/server.ts";

export const handler: Handlers = {
    async POST(req: Request, ctx: HandlerContext){
        const payload = await req.body
        console.log(payload)
        return new Response(payload)
    }
};

Solution

  • The data is in the request body, but it has to be read from the ReadableStream in chunks of bytes. You can do this with a for await loop:

    for await (const chunk of req.body) {
      // Do stuff
    }
    

    So if for example you wanted to just log the data, the handler would look something like this:

    export const handler: Handlers = {
      async POST(req: Request, ctx: HandlerContext){
          const payload = req.body
    
          if (payload === null) {
            return new Response("Invalid request: body is null");
          }
    
          const decoder = new TextDecoder()
          for await (const chunk of payload) {
            // decode the bytes into a string and print it
            console.log(decoder.decode(chunk))
          }
    
          return new Response(payload)
      }
    };