Mohamed Shaheen
Mohamed Shaheen

Reputation: 663

How to make http request using wix?

I have a Wix website and I am trying to make API requests to a mobile app I have a database called Stores which have a collection called Products

My question is how to make a get request to get all values in the collection Products ? my code below is not working

http-functions.js

import {ok, notFound, serverError} from 'wix-http-functions';
import wixData from 'wix-data';


export function get_example(request) {
    const response = {
        "headers": {
            "Content-Type": "application/json"
        }
    };

    return wixData.query("Products")
    .find()
    .then(
        result=> {
            response.body = {
            "items": result.items
        };
        return ok(response);
        }
    )
}

I get this error

{"error":{"name":"Error","errorGroup":"User","code":"WD_VALIDATION_ERROR"}}

Upvotes: 0

Views: 2485

Answers (1)

Shan
Shan

Reputation: 958

I am trying to make API requests to a mobile app

You are trying to make API request TO a mobile App? If so, you need to use wix-fetch.

If you are trying to make a request FROM a mobile app TO your Wix site then you are on the right track. You will need to make a call like below.

import {ok, notFound, serverError} from 'wix-http-functions';
import wixData from 'wix-data';

export function get_getNewItems(request) {
    let options = {
    "headers": {
        "Content-Type": "application/json"
        }
    };
    return getItems(options)
    .catch( (error) => {
        options.body = {
            "origin": "server error",
            "error": error
        };
        return serverError(options);
    });
}

function getItems(options) {
    return wixData.query("Stores/Products")
    .find()
    .then( (results) => {
      // matching items were found
        if(results.items.length > 0) {
            options.body = {
                "origin": "success",
                "items": results.items
            };
            return ok(options);
        } else {
        // no matching items found
            options.body = {
                "origin": "no items",
                "error": 'No items found'
            };
            return notFound(options);
        }
        });
}

Upvotes: 2

Related Questions