beforeInsert hook and fetch

I have a form, which is connected to a database table. Before it is inserted, I want to add some stuff to it from another server. To do this, I am trying to use a beforeInsert hook that attempts to use fetch:

import {fetch} from 'wix-fetch';
export function TrialRequest_beforeInsert(item, context) {
	return fetchRequest(item);
}

function fetchRequest(item){
	let url = "https://api.fixer.io/latest";
	fetch(url, {method: 'get'})
	.then((httpResponse) => {
		if (httpResponse.ok) {
	  		return httpResponse.json();
		}
		else {
			return Promise.reject("Fetch did not succeed");
		}
	})
	.then((json) => {
		item.extra = JSON.stringify(json);
		return item;
	})
	.catch( (err) => {
		item.extra = err;
		return item;
	});
}

However I am getting the error:
Hook beforeInsert for collection TrialRequest result ignored! Expected hook result to resolve to an object, but got [Undefined]

Any tips on what I’m doing wrong?

In fact, the other server never even receives the get request (as observed in its access logs), which is puzzling. Is it even possible to do a fetch in a hook?

OK figured this out. I forgot to put “return” in front of “fetch”:

return fetch(url, {method: 'get'})

Also, other tips that may be useful for somebody tryuing to set up something like this:
• If your wix website is SSL-enabled, you will not be able to fetch from http, only from https
• If the remote server has https but is using a self signed certificate, you will also get an error
• You also need to allow CORS on the remote server (e.g. by adding the following line to .htaccess; instead of * you could add actual allowed request source)

Header set Access-Control-Allow-Origin "*"

Hello Eugene, I am trying to do something similar, but with a post request. I have to pass in the headers
Content Type : application/json
user: API key
pass: API secret

I need to add fields from my form to the request. Not exactly sure how to so this. The fields are address and zipcode. I have not tried your modifying your code yet, but will tonight. If you have any suggestions I would appreciate.

You just add HTTP headers as an additional object after ‘method’.
Below shows how to use Content-Type header.
Note that there is a dash in “Content-Type”. Also all header content may be case and punctuation sensitive, so be super careful with what you are putting into the headers, or it can get ignored or even cause an error.

import {fetch} from 'wix-fetch';

$w.onReady(function () {

	myFetch().then((result) => {
		console.log(result);
	});


});

function myFetch(){
	let url = "https://api.fixer.io/latest";
	return fetch(url, {
		method: 'get',
		headers: {
			'Content-Type':'application/json'
		}
	})
	.then((httpResponse) => {
		if(httpResponse.ok){
			return httpResponse.json();
		}
		else {
			return Promise.reject("Fetch failed");
		}
	})
	.then((json) => {
		let s = JSON.stringify(json);
		return s;
	})
	.catch( (err) => {
		console.log("Error: ");
		console.log(err);
	});
}

‘user’ and ‘pass’ are not HTTP headers, so you probably want to try to add them to the URL as GET parameters. I would presume that the same applies to form fields. E.g.:

https://example.com/page/?user=whoami&pass=helloworld

However, it may be that you require some other form of authentication which in fact could be passed via headers but in a more long-winded way. Try to check how authentication works there first.

Yes authentication is basic. I am trying to convert the follow code to wix code splitting it between my hook in data.js file and my forms page code. I can not send the user and pass in the URL because they are my private API key and API secret.

Example with Node.js

const request = require(‘request’);

const url = ‘https://api.housecanary.com/v2/property/value’;

const postData = [

{‘address’: ‘43 Valmonte Plaza’, ‘zipcode’: ‘90274’},

{‘address’: ‘7500 Melrose Ave’, ‘zipcode’: ‘90046’}

];

request.post({

url: url,

auth: {

user: 'my_api_key', 

pass: 'my_api_secret' 

},

body: postData,

json: true

}, function (error, response, body) {

console.log(body);

});

Sorry let me revise just a bit. My page code is simply saving to my collection. I need the code from my previous post converted to wix code to make the Post request beforeInsert grabbing the post response to be added to the collection. Thanks again.

Have you tried to put authentication into headers?

headers: {
	'Content-Type':'application/json',
	'Authorization':'Basic '+btoa(username+":"+password)
}

I don’t, know if WixCode has the btoa() function, but try it first.