Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Unable to get body of POST request to custom endpoint

default discord avatar
jakey___2 years ago
28
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
    notchr2 years ago
    @214419801039175682

    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___2 years ago
    req.params

    returns a

    {}

    (sorry, multi-tasking lol)

  • default discord avatar
    notchr2 years ago

    Hey

    @214419801039175682

    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

  • default discord avatar
    jakey___2 years 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
    notchr2 years ago

    Sounds good, let me know!

  • default discord avatar
    jakey___2 years 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
    notchr2 years ago

    hmm



    Can we see your payload config?

  • default discord avatar
    jakey___2 years 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
    notchr2 years ago

    endpoints is an array of objects, right?

  • default discord avatar
    jakey___2 years ago

    yup yup

  • default discord avatar
    notchr2 years ago

    what is the response code of the request?



    200?

  • default discord avatar
    jakey___2 years ago

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

  • default discord avatar
    notchr2 years ago
  • default discord avatar
    jakey___2 years ago

    that is what the end request is yes

  • default discord avatar
    notchr2 years ago

    and that's a 404?

  • default discord avatar
    jakey___2 years ago

    yes

  • default discord avatar
    notchr2 years 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___2 years ago

    checking

  • default discord avatar
    notchr2 years ago

    i think yours should just be /api/

  • default discord avatar
    jakey___2 years ago

    ohh ok, yes, /api/foo worked

  • default discord avatar
    notchr2 years ago

    NICE

  • default discord avatar
    jakey___2 years ago

    and the post body came through



    😄

  • default discord avatar
    notchr2 years ago

    Yayyyy

  • default discord avatar
    jakey___2 years ago

    thank you so much!

  • default discord avatar
    notchr2 years ago

    Of course!

  • default discord avatar
    wizen3380last year
    @1049775120559898725

    I think

    root: true

    is missing body parser

  • default discord avatar
    notchrlast year
    @760227653403148349

    Hmm sorry what do you mean/

  • default discord avatar
    wizen3380last year
    @1049775120559898725

    once you have

    root: true

    on the custom endpoint, req.body is empty. It's not empty when

    root: false
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.