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.

const body = await req.json() not working

default discord avatar
teneburulast year
26

Hi, I'm trying to access the body of my requests and I can't make it work...



I'm getting Unexpected end of JSON input every time i fire a request to this :



  path: '/test',
  method: 'get',
  handler: async (req) => {
    const body = await req.json()
    console.log(body)
    return new Response('OK', { status: 200 })
  },


my IDE tells me


Cannot invoke an object which is possibly 'undefined'.


'req.json' is possibly 'undefined'.



looks like everyone else does it like this, why can't I ?

  • default discord avatar
    .quantranlast year

    What is this? I don't recognize Next.js or Payload in this code.

  • default discord avatar
    teneburulast year

    this is my first try at making a custom endpoint, here is the full file that i reference in


    endpoints: [
      test,
    ],

    in a collection config

  • default discord avatar
    .quantranlast year

    Let me try, I don't know they have this feature 😄



    af



    you are using GET

  • default discord avatar
    teneburulast year

    ah

  • default discord avatar
    .quantranlast year

    get method don't have body

  • default discord avatar
    teneburulast year

    ofc...



    i'm so bad 😩 i need a break



    too much stress

  • default discord avatar
    .quantranlast year

    haha, it's weekend, enjoying it instead of stress bro

  • default discord avatar
    teneburulast year

    my client has put me through this... at least i'm paid... but time for coffee



    thank you !!



    @420245280404013076

    it doesn't work even with post...



  • default discord avatar
    adrian8749last year

    try

    req?.json && await req.json()

    or sth



    typescript should indicate that

  • default discord avatar
    teneburulast year
    curl -X POST http://localhost:3000/api/media/test
    
    {"errors":[{"message":"Something went wrong."}]


    with this the ide doesn't show typescript error anymore but the result is the same, the server logs Unexpected end of JSON input

  • default discord avatar
    adrian8749last year

    show me full code

  • default discord avatar
    .quantranlast year


    try to remove .next folder



    stop dev then remove .next folder then start dev again



    why your url is api/media/test?

  • default discord avatar
    teneburulast year

    i'm in a plugin create-payload-app template by the way, the endpoint is in



    export default buildConfig({
      admin: {
        autoLogin: devUser,
        importMap: {
          baseDir: path.resolve(dirname),
        },
      },
      collections: [
        {
          slug: 'posts',
          fields: [],
        },
        {
          slug: 'media',
          fields: [],
          upload: {
            staticDir: path.resolve(dirname, 'media'),
          },
          endpoints: [test],
        },
      ],
  • default discord avatar
    .quantranlast year

    do you try request to api/test?

  • default discord avatar
    adrian8749last year

    Show me also fetch request, and please provide test.ts in discord brackets as I am on phone

  • default discord avatar
    teneburulast year

    it's api/media/test it returns error, /api/test returns 404 in server logs



    import { Endpoint, PayloadRequest } from 'payload'
    
    export const test: Endpoint = {
      path: '/test',
      method: 'post',
      handler: async (req: PayloadRequest) => {
        const body = req?.json && (await req.json())
        console.log(body)
        return new Response('OK', { status: 200 })
      },
    }
  • default discord avatar
    .quantranlast year

    could you show me how you make the request to /api/test?

  • default discord avatar
    adrian8749last year

    Yeah show fetch request

  • default discord avatar
    teneburulast year

    oh i managed to do it ?



    i used curl to do the request not a fetch()



    i think i just had a bad syntax on -d it works now

  • default discord avatar
    .quantranlast year

    copy and past the curl here, or screenshot it

  • default discord avatar
    adrian8749last year

    Personally I recommend axios for frontend

  • default discord avatar
    teneburulast year

    will do !



    don't worry it's okay now

  • default discord avatar
    .quantranlast year

    🤡 you need go to bed dude



    😄 good to hear it, i'm sleep now

  • default discord avatar
    teneburulast year

    it's 6pm here, but i do need to sleep for like a week like a polar bear





    have a good night!!

  • default discord avatar
    paulpopuslast year

    we get this error internally in payload as well, in some cases the body isnt available OR the stream abruptly ends via cancellation or something from the browser

  • default discord avatar
    teneburulast year

    oh i'm not so crazy then !!



    i don't know how i fixed it, i changed the syntax of my curl, i added allowImportingTsExtensions in ts.config, and i moved the endpoint file's relative path all at once and on next request it was working

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.