简体   繁体   中英

Remix api parse request body

Im creating a api route that will handle a post request, the main idea is to create an api endpoint to add data. The problem is I can not get the data sent to the endpoints.

// posts-creation.ts
export const action: ActionFunction = async ({ request }) => {
  switch (request.method) {
      case 'POST': {
        return json(request.body);
      }
  }
}

But when I use postman to do post request with a JSON body shows this

{
"_readableState": {
    "objectMode": false,
    "highWaterMark": 16384,
    "buffer": {
        "head": null,
        "tail": null,
        "length": 0
    },
    "length": 0,
    "pipes": [],
    "flowing": null,
    "ended": false,
    "endEmitted": false,
    "reading": false,
    "sync": false,
    "needReadable": false,
    "emittedReadable": false,
    "readableListening": false,
    "resumeScheduled": false,
    "errorEmitted": false,
    "emitClose": true,
    "autoDestroy": true,
    "destroyed": false,
    "errored": null,
    "closed": false,
    "closeEmitted": false,
    "defaultEncoding": "utf8",
    "awaitDrainWriters": null,
    "multiAwaitDrain": false,
    "readingMore": false,
    "dataEmitted": false,
    "decoder": null,
    "encoding": null
},
"_events": {
    "error": [
        null,
        null,
        null,
        null
    ]
},
"_eventsCount": 5,
"_writableState": {
    "objectMode": false,
    "highWaterMark": 16384,
    "finalCalled": false,
    "needDrain": false,
    "ending": false,
    "ended": false,
    "finished": false,
    "destroyed": false,
    "decodeStrings": true,
    "defaultEncoding": "utf8",
    "length": 0,
    "writing": false,
    "corked": 0,
    "sync": true,
    "bufferProcessing": false,
    "writecb": null,
    "writelen": 0,
    "afterWriteTickInfo": null,
    "buffered": [],
    "bufferedIndex": 0,
    "allBuffers": true,
    "allNoop": true,
    "pendingcb": 0,
    "prefinished": false,
    "errorEmitted": false,
    "emitClose": true,
    "autoDestroy": true,
    "errored": null,
    "closed": false
},
"allowHalfOpen": true

}

Any idea how to parse the response and get the body data without having to install other packages?

You can do:

const data = await request.json();
return json({ data });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM