Getting Request Body in API / Webhook Endpoint

To test my understanding of Wix and webhooks, I created a simple Wix endpoint in http-functions.js . My aim is simply to deliver a JSON payload to the endpoint as a POST request and then echo that same payload back as the response. However, I can’t figure out how to get the body of the request.

Here’s my code:

import { ok } from 'wix-http-functions';
export function post_myWebhook(request) {
	let options = {
		"headers": {
			"Content-Type": "application/json",
		},
//		"body": request.body.json() // returns {"_c":[],"_s":0,"_d":false,"_h":0,"_n":false}
//		"body": request.body // returns {} (empty object)
		"body": { "foo" : "bar" } // works
	};
	return ok( options );
}

I get what I expect only when I hard code a JS object as the value of the “body” property. What I really want, though, is the body (payload) that was passed in the request.

I’m using Postman to send the request, and I’ve verified it’s configure properly by posting to requestb.in. I just can’t seem to get the desired result in Wix.

Can anyone shed some light on what I’m doing wrong?

Thanks much!

Hi Steve,
Calling body.text() returns a promise, so you need to wait for it. You can see an example in the docs:

Thanks for the reply, Tomer. Yeah, I did try that as well. I copied and pasted directly from the docs and modified it to suit my needs, but no joy. I’ll give it another go tomorrow and post my code here if I still have no success.

I don’t have a lot of experience with promises yet, so that could be part of the problem. :confused:

We are also allowing a newer JS syntax called “async await”, that allows you to write asynchronous code (promises) using a synchronous-like syntax. I converted your example:

import { ok } from 'wix-http-functions';
export async function post_myWebhook(request) {
	const bodyJson = await request.body.json();
	let options = {
		"headers": {
			"Content-Type": "application/json",
		},
		"body": bodyJson
	};
	return ok( options );
}

Compared to the promises way:

import { ok } from 'wix-http-functions';
export function post_myWebhook(request) {
	return request.body.json().then(bodyJson => {
		let options = {
			"headers": {
				"Content-Type": "application/json",
			},
			"body": bodyJson
		};
		return ok( options );
	})
}

Both ways work like a charm! Thanks much, Tomer! (I had forgotten the “return” before the “request” statement in my first promise attempt.)

FWIW, I much prefer the “async await” syntax - cleaner and easier to understand IMO.

I agree (although it has its small pitfalls as well). We will be recommending it more in the future.