0

So I have been struggeling with this problem today. But can't find propper documentation about it.

I have a Vue.js/ES6 front-end and a Node.js back-end with Hapines.

I am at the point where I want to insert data into the database via a POST request from the front-end to the back-end.

Currently I have this code

Front-end:

saveOrder(){
    let Nes = require('nes');
    let appClient = new Nes.Client('ws://localhost:3000');
    appClient.connect((err) => { console.log(err); });

    let options = {
        path: '/order',
        method: 'POST',
        payload: this
    };

    appClient.request(options, (err, payload) => {
      console.log(payload);
    });
}

Back-end

server.route({
    method: 'POST',
    path: '/order',
    config: {
        id: 'order',
        handler: (request, reply) => {
            return reply('Request came through');
        }
    }
})

This is the JSON object I send to the server

{
  "path": "/order",
  "method": "POST",
  "payload": {
    "products": [{
        "id": 2,
        "plu": "1AB23CD",
        "name": "Some name",
        "description": "Some description",
        "barcode": "123456789",
        "sellUnitID": 1,
        "taxGroupID": 1,
        "labelID": 1,
        "defaultPrice": 1,
        "sellAmount": 1,
        "archived": 0
    }]
  }
}

When I make the call, it just returns undefined.

Is there someone who could help me with this, or has some form of documentation where POST requests with Hapines are better explained then the Hapines Github page?

All help would be appreciated!

Bas Pauw
  • 262
  • 1
  • 12

1 Answers1

0

You need to move let options = {...} and appClient.request(...) inside the connect callback. connect executes asynchronously and uses the callback pattern, a common pattern in javascript. You'll also need to declare a reference to this at the top of your function because of how scoping works inside of functions.

In your case right now, you're trying to make a websocket request before it's actually connected to your server.

function saveOrder() {
    let self = this;

    let Nes = require('nes');
    let appClient = new Nes.Client('ws://localhost:3000');

    appClient.connect((err) => {

        if (err) {
            console.log(err);
            throw err;
        }

        let options = {
            path: '/order',
            method: 'POST',
            payload: self
        };

        appClient.request(options, (err, payload) => {
            console.log(payload);
        });
    });
}
Cuthbert
  • 2,908
  • 5
  • 33
  • 60