Velo fetch within post handler method

Question:
I’m trying to create a Velo post method that does a fetch with the body of the post request. In the backend Wix Editor I created this method that works fine when I run it from the editor but when I call it as a post it doesn’t work. I’ve tried other ways but can’t get it to work.

Please show me sample code that does a fetch with the body of the post request.

The method:

import {fetch} from 'wix-fetch';

import { ok, badRequest } from 'wix-http-functions';

export async function post_Call(request) {
  
  const fetchOptions = {
    method: 'post',
    headers: 'application/json',
    body: JSON.stringify(request.body)
  };

  const response = await fetch('https://wallmirror.com/_functions/myFunction3', fetchOptions); 
  return response.json();
}

Here’s sample request data.

{
    "request": {
        "path": [
            "myPath1",
            "myPath2"
        ],
        "headers": {
            "Accept": "*/*"
        },
        "query": {
            "myKey": "myValue"
        },
        "method": "GET",
        "body": {
            "from": "John",
            "to": "Sue",
            "body": "Hello World"
            }
    }
}

Can you share how myFunction3 is defined?

Hi,

Function3 just returns the body of the caller. Here’s the code:

export function post_myFunction3(request) {
  let options = {
    "headers": {
      "Content-Type": "application/json"
    },
    "statusCode": 200,
    "reqbody": {}
  };
  // get the request body
  return request.body.json()
  .then( (body) => {
      options.body = body;
       return created(options);
    } )
      .catch( (error) => {
     options.body = {
        "error": error
      }
    
     return serverError(options);
   } );
}

Got it. Are you getting an error message? Can you share that if so?

I get 500 server error

Hi Anthony,

You do not need to debug my code. I would take any sample of post code that can do a fetch using the post body.

Thanks,
Ross

This is why I’m asking because your code should work.

I think this might be the cause of the issue. headers should be an object like:

  const fetchOptions = {
    method: 'post',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(request.body)
  };

Here’s a full example from my tests:

import {fetch} from 'wix-fetch';

export async function postRequest(request) {
  
  const fetchOptions = {
    method: 'post',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(request.body)
  };

  const response = await fetch('https://website/_functions/myFunction3', fetchOptions); 
  return response.json();
}
$w.onReady(function () {
	let request = {
		body: {
			key: "value"
		}
	}
	postRequest(request).then((result) => {
		console.log(result);
	})
});

// returns {key: 'value'}

Hi Anthony,

Is this code for the backend? I tried using it as a backend function and got a compile message: cannot use $w namespace as a value.

Ross

This is frontend code. I was just testing it out in the frontend.

The backend equivalent would just be the first half of the code:

import {fetch} from 'wix-fetch';

export async function postRequest(request) {
  
  const fetchOptions = {
    method: 'post',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(request.body)
  };

  const response = await fetch('https://website/_functions/myFunction3', fetchOptions); 
  return response.json();
}

and then calling postRequest(request) from somewhere (like running it from the editor in functional testing).

Hi Anthony,

I’m primarily interested in doing this on a backend post I would also like to know if there is anyway to do logging on backend post or get requests. It has been hard to debug this.

Here is an example of a backend get request handler that works. I can take the values of URL query variables and uses them in my fetch. I just want to equivalent code in a post request handler.

export function get_fetchWithGet(request) {
  //console.log('request.body: ' + JSON.stringify(request.body));
  const inFrom = '+' + request.query["from"];
	const inTo = '+' + request.query["to"];
	const inBody = request.query["body"];

  const data = {
		"from": inFrom,
		"to": inTo,
		"body": inBody
	};
	const options = {
		'method': 'POST',
		'headers': {
			'Content-Type': 'application/json'
		},
        "statusCode": 200,
		'body': JSON.stringify(data)
	};

  
    fetch('https://website/_functions/myFunction3', options)
            .then(response => {
                 response.json()
            })
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));
       
    return created(options);
}

So the only issue with the original code was when it was making the post request, not the code handling the post request.

The original fetchOptions was this which didn’t work:

As for logging yes you can do that. console.log and console.error will print to your site logs when used on the backend. You can either use Wix’s builtin logging that only records and displays logs when you have the log page open, or you can use external providers like Google Operations to get persistent logs. More info on this here: About Logs (formerly Site Monitoring)