Unable to get body of POST request to custom endpoint

default discord avatar
jakey___
4 months ago
48
const response = await fetch(`/path/to/custom/endpoint`, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(theData),
})


I'm attempting to get the post body from the

req

object in the endpoint handler:



const customEndpoint :Endpoint = {
    path: '/path/to/custom/endpoint',
    method: 'post',
    root: true,
    handler: async (req, res, next) => {
        try {
            console.log(req.body) // undefined :(
            res.status(200).send({
                message: 'Request successful',
            })
        }
        catch (err) {
            console.error(err)
            res.status(500).send({
                message: 'Error occurred during request',
                error: err,
            })
        }
    },
}

I also attempted this with a

application/x-www-form-urlencoded

content-type and nothing appears to be parsing the post body.

  • default discord avatar
    notchr
    4 months ago

    @jakey___ That's odd, you should get the body back, is the req undefined as well?



    Also, is customEndpoint passed in the endpoints array of your Payload Config?



    Also, how about req.params?

  • default discord avatar
    jakey___
    4 months ago
    req.params

    returns a

    {}


    (sorry, multi-tasking lol)

  • default discord avatar
    notchr
    4 months ago

    Hey @jakey___



    So I just added that endpoint to my payload config



    const customEndpoint: Endpoint = {
      path: "/foo",
      method: "post",
      handler: async (req, res, next) => {
        try {
          console.log(req.body);
          res.status(200).send({
            message: "Request successful",
          });
        } catch (err) {
          console.error(err);
          res.status(500).send({
            message: "Error occurred during request",
            error: err,
          });
        }
      },
    };


    I removed "root: true"



    And then with postman I hit



    http://localhost:3000/payload/api/foo with

    {"hello":"world"}`





    And it looks like it logged the req.body correctly

    image.png
  • default discord avatar
    jakey___
    4 months ago

    niice! i did wonder if setting root to true was messing with things. I only did that in the first place because I wasn't aware the prefix was

    /payload/api


    i'll give that a try and report back

  • default discord avatar
    notchr
    4 months ago

    Sounds good, let me know!

  • default discord avatar
    jakey___
    4 months ago

    huh, yeah i don't know why i keep getting 404's when i attempt the removal of

    root:true


    copy/pasted your code in and it's still 404'ing



    to answer your earlier question, yes, the endpoints is an array



    and

    req

    itself is not undefined



    just missing the body prop

  • default discord avatar
    notchr
    4 months ago

    hmm



    Can we see your payload config?

  • default discord avatar
    jakey___
    4 months ago

    sure sec



    so all my config is in this plugin i'm writing which looks like this

    import path from 'path'
    import { Config, Plugin } from 'payload/config'
    import AfterNavLinks from './afterNavLinks'
    import endpoints from './endpoints'
    import Terms from './collections/Terms'
    import TermsManagerUi from './ui'
    import TermsManagerImporterUi from './ui/importer'
    
    const termsManager :Plugin = (incomingConfig :Config) :Config => {
        const config :Config = {
            ...incomingConfig,
            admin: {
                ...incomingConfig.admin,
                components: {
                    ...incomingConfig.admin.components,
                    routes: [
                        {
                            Component: TermsManagerUi,
                            path: '/tools/terms-manager',
                        },
                        {
                            Component: TermsManagerImporterUi,
                            path: '/tools/terms-manager-import',
                        },
                    ],
                    afterNavLinks: [ AfterNavLinks ],
                },
                webpack: (config) => {
                    const newConfig = {
                        ...(config || {}),
                        resolve: {
                            ...(config.resolve || {}),
                            alias: {
                                ...(config.resolve.alias || {}),
    ...[
                                    'mssql',
                                    'fs',
                                ].reduce((c, i) => ({
                                    ...c,
                                    [i]: path.resolve(__dirname, `mocks/emptyObject.js`)
                                }), {}),
                            },
                        },
                    }
                    return newConfig
                },
            },
            endpoints: [ ...endpoints ],
            collections: [
                ...incomingConfig.collections,
                Terms,
            ],
        }
        return config
    }
    
    export default termsManager


    then in the original config, i just include the plugin

  • default discord avatar
    notchr
    4 months ago

    endpoints is an array of objects, right?

  • default discord avatar
    jakey___
    4 months ago

    yup yup

  • default discord avatar
    notchr
    4 months ago

    what is the response code of the request?



    200?

  • default discord avatar
    jakey___
    4 months ago

    404 atm. when i set it to /foo without root

  • default discord avatar
    notchr
    4 months ago
  • default discord avatar
    jakey___
    4 months ago

    that is what the end request is yes

  • default discord avatar
    notchr
    4 months ago

    and that's a 404?

  • default discord avatar
    jakey___
    4 months ago

    yes

  • default discord avatar
    notchr
    4 months ago

    ok what about



    http://localhost:3000/api/foo


    404?



    the default prefix isnt /payload/api, i manually do that in my config

  • default discord avatar
    jakey___
    4 months ago

    checking

  • default discord avatar
    notchr
    4 months ago

    i think yours should just be /api/

  • default discord avatar
    jakey___
    4 months ago

    ohh ok, yes, /api/foo worked

  • default discord avatar
    notchr
    4 months ago

    NICE

  • default discord avatar
    jakey___
    4 months ago

    and the post body came through



    😄

  • default discord avatar
    notchr
    4 months ago

    Yayyyy

  • default discord avatar
    jakey___
    4 months ago

    thank you so much!

  • default discord avatar
    notchr
    4 months ago

    Of course!

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.