Search code examples
javascriptnode.jsangularjsvelo

How to get access to Wix DB - Blog Posts


So right now I have a homepage, made by using html. I want to add some divs, where I show the newest blogs I posted on my WIX page.

<div layout="row" layout-align="center center">
   <md-card flex="60" class="pad-md md-body-1 border-1" md-colors="{&quot;borderColor&quot;: &quot;epprimary1-500&quot;, &quot;color&quot;: &quot;epsecondary6&quot;}">
      {{blog headline}}
      <a href="{{blog link}}">Open Blog<md-icon>open_in_new</md-icon></a>
   </md-card>
</div>

On the Wix platform, I know where they store the data in a so called dataset:

Wix Dataset

Now I need to know how to access these data from my other website.


Solution

  • I figured it out, finally!!

    You can get the data you need via an http request. Therefore, first of all, you need to add a javascript in your backend folder in Wix and name it "http-functions.js", delete it's content and add the folowing code.

    Note: get_blogEntry() is method_functionName()

    Blog/Posts is the DB I used, you can use any DB you have on wix.

    import {ok, notFound, serverError} from 'wix-http-functions';
    import wixData from 'wix-data';
    export function get_blogEntry() {
      let options = {
        "headers": {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
        }
      };
    // query a collection to find matching items
    return wixData.query("Blog/Posts")
    .find()
    .then( (results) => {
      // matching items were found
      if(results.items.length > 0) {
        let itemOne = results.items[0];
        let itemTwo = results.items[1];
    
        options.body = {
            "blogOneTitle": itemOne.title,
            "blogOneUrl": "https://etaplus.energy" + itemOne.postPageUrl,
            "blogTwoTitle": itemTwo.title,
            "blogTwoUrl": "https://etaplus.energy" + itemTwo.postPageUrl
        }
        return ok(options);
      }
    })
    // something went wrong
    .catch( (error) => {
      options.body = {
        "error": error
      };
      return serverError(options);
    } );
    }
    

    After you added this code in your backend, then you can access the data via the following URL:

    "https://YOURWEBSITEURL/_functions/blogEntryor whatever your function name is"