Extract Post Data From Request

At a loss here on why my post data is not being captured in the request.

My Post

    React.useEffect(() => {
        if (readyToSave) {
            axios.post('/wxc/api/custom_css_server/saveObjectCss', {
                id: modalData.id,
                code: modalData.code
            }, {
                headers: {
                    "Content-Type": "application/json",
                    "kbn-xsrf": "anything",
                    Accept: "application/json, text/plain, */*",
                },
            })
                .then((response) => {
                    console.log(response);
                }, (error) => {
                    console.log(error);
                });

        }
    }, [readyToSave]);

My Route

import { IRouter } from '../../../../src/core/server';

export function saveObjectCss(router: IRouter) {
    router.post(
        {
            path: '/api/custom_css_server/saveObjectCss',
            validate: false,
        },
        async (context, request, response) => {

            console.log(response)
            console.log(request)
            console.log(context)


            return response.ok({ body: `Where's my post data?` });

        }
    );
}

The Request

KibanaRequest {
  params: {},
  query: {},
  body: {},
  withoutSecretHeaders: true,
  url:
   Url {
     protocol: null,
     slashes: null,
     auth: null,
     host: null,
     port: null,
     hostname: null,
     hash: null,
     search: null,
     query: [Object: null prototype] {},
     pathname: '/api/custom_css_server/saveObjectCss',
     path: '/api/custom_css_server/saveObjectCss',
     href: '/api/custom_css_server/saveObjectCss' },
  route:
   { path: '/api/custom_css_server/saveObjectCss',
     method: 'post',
     options:
      { authRequired: true,
        xsrfRequired: true,
        tags: [],
        body: [Object] } },
  headers:
   { host: 'localhost:5603',
     connection: 'keep-alive',
     'content-length': '61',
     accept: 'application/json, text/plain, */*',
     'kbn-xsrf': 'anything',
     'user-agent':
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36',
     'content-type': 'application/json',
     origin: 'http://localhost:5603',
     'sec-fetch-site': 'same-origin',
     'sec-fetch-mode': 'cors',
     'sec-fetch-dest': 'empty',
     referer: 'http://localhost:5603/wxc/app/customCssServer',
     'accept-encoding': 'gzip, deflate, br',
     'accept-language': 'en-US,en;q=0.9' },
  isSystemRequest: false,
  socket:
   KibanaSocket {
     socket:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: [TCP],
        _parent: null,
        _host: null,
        _readableState: [ReadableState],
        readable: true,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: true,
        allowHalfOpen: true,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Server],
        _server: [Server],
        timeout: 120000,
        parser: [HTTPParser],
        on: [Function: socketOnWrap],
        _paused: false,
        _httpMessage: [ServerResponse],
        _isHapiProcessing: true,
        _peername: [Object],
        [Symbol(asyncId)]: 91643,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]:
         Timeout {
           _called: false,
           _idleTimeout: 120000,
           _idlePrev: [TimersList],
           _idleNext: [Timeout],
           _idleStart: 571142,
           _onTimeout: [Function: bound ],
           _timerArgs: undefined,
           _repeat: null,
           _destroyed: false,
           [Symbol(unrefed)]: true,
           [Symbol(asyncId)]: 101548,
           [Symbol(triggerId)]: 91647 },
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0 },
     authorized: undefined,
     authorizationError: undefined },
  events:
   { 'aborted$':
      Observable {
        _isScalar: false,
        source: [Observable],
        operator: [TakeUntilOperator] } },
  auth: { isAuthenticated: true } }

The response back

config:
data: "{"id":"edf84fe0-e1a0-11e7-b6d5-4dc382ef7f5b","code":"aaron2"}"

I verified the request is being sent and I even get the data back in the response. But I can't seem to figure out how access my post data in the router.

Any hint is appreciated.

Figured it out. When you do a POST you have to validate. Only a GET can be validate: false.

So import the schema and validate your data like below. Odd it requires you to validate but I guess it's a security reason.

import { IRouter } from '../../../../src/core/server';
import { schema } from '@kbn/config-schema';

export function saveObjectCss(router: IRouter) {
    router.post(
        {
            path: '/api/custom_css_server/saveObjectCss',
            validate: {
                body: schema.object({
                    id: schema.string(),
                    code: schema.string(),
                }),
            },
        },
        async (context, request, response) => {

            console.log(response)
            console.log(request)
            console.log(context)

            return response.ok({ body: `Where's my post data?` });

        }
    );
}
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.