【问题标题】:POST request with Hapines js使用 Hapines js 的 POST 请求
【发布时间】:2017-05-16 21:43:43
【问题描述】:

所以我今天一直在努力解决这个问题。但是找不到关于它的适当文档。

我有一个 Vue.js/ES6 前端和一个带有 Hapines 的 Node.js 后端。

我现在想通过从前端到后端的 POST 请求将数据插入数据库。

目前我有这个代码

前端:

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);
    });
}

后端

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

这是我发送到服务器的 JSON 对象

{
  "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
    }]
  }
}

当我拨打电话时,它只返回undefined

有没有人可以帮助我解决这个问题,或者有某种形式的文档,其中 Hapines 的 POST 请求比 Hapines Github 页面解释得更好?

所有帮助将不胜感激!

【问题讨论】:

    标签: javascript json http-post hapijs


    【解决方案1】:

    您需要在connect 回调中移动let options = {...}appClient.request(...)connect 异步执行并使用 callback pattern,这是 javascript 中的常见模式。由于scoping works inside of functions 的方式,您还需要在函数顶部声明对this 的引用。

    在您现在的情况下,您正在尝试在 websocket 实际连接到您的服务器之前发出请求。

    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);
            });
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 2021-07-08
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多