Friday, 12 May 2017

Restify Client,post does not return => Socket hang up

Server.js

var restify = require('restify'),
    products = require('./products'),
    port = process.env.PORT || 3000;

var server = restify.createServer({
    name : 'simple restify server'
});

server.use(function(req,res,next){
    console.log(req.method + ' ' + req.url);
    return next();
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
/*server.use(function (error, req, res, next) {
  if (!error) {
    next(); 
  }else{
    console.error(error);
    }
});*/

server.get('api/products',products.get);
server.get('api/products/:id',products.getById);
server.post('api/product',products.post);
server.put('api/products/:id',products.put);
server.del('api/products/:id',products.del);

server.listen(port, function(){
    console.log('api running at ' + port);
});

module.exports = server;

Products.js

function ProductsController(){
    var that = this,
        mongojs = require('mongojs'),
        db = mongojs('mongodb://database@database/database',['products'])
    that.store = [];

    var findProductById = function(req){
        var found = that.store.filter(function(p){
            return p.Id === parseInt(req.params.id);
        });
        if(found && found.length>0){
            return found[0];
        }
        return null;
    };

    that.get = function(req,res,next){
        db.products.find(function(err, products){
            res.writeHead(200, {
                'Content-Type' : 'application/json; charset=utf-8'
            });
            res.end(JSON.stringify(products));
        });
        return next();
    };

    that.getById = function(req,res,next){
        var found = findProductById(req);
        if(found){
            res.send(200,found);
        }else{
            res.send(404,"product not found");
        }
        return next();
    };

    that.post = function(req,res,next){
        var product = req.params;

        db.products.save(product, 
            function(err, data){
                res.writeHead(200, {
                    'Content-Type' : 'application/json; charset=utf-8',
                    'Content-Length': Buffer.byteLength(data)
                });
                res.end(JSON.stringify(products));
            });
        return next();
    };

    that.put = function(req,res,next){
        if(!req.body.hasOwnProperty('name')){
            res.send(500);
            return next();
        }
        var found = findProductById(req);
        if(found){
            found.name = req.body.name;
            res.send(200,found);
        }else{
            res.send(404,"product not found");
        }
        return next();
    };

    that.del = function(req,res,next){
        that.store = that.store.filter(function(p){
            return p.id !== parseInt(req.params.id);
        });
        res.send(200);
        return next();
    };
};

module.exports = new ProductsController();

Client.js

var restify = require('restify');
var server = require('./server');

var client = restify.createJsonClient({
    url: 'http://localhost:3000',
    agent: false
});

// a static product to CREATE READ UPDATE DELETE

var testProduct = {
    "id": "1",
    "name": "Apple iPad AIR",
    "os": "iOS 7, upgradable to iOS 7.1",
    "chipset": "Apple A7",
    "cpu": "Dual-core 1.3 GHz Cyclone (ARM v8-based)",
    "gpu": "PowerVR G6430 (quad-core graphics)",
    "sensors": "Accelerometer, gyro, compass",
    "colors": "Space Gray, Silver"
};

client.on('error', function (err) {
   console.error('I would have blown up: ' + err.toString());
});

client.post('/api/product', testProduct, function (err, req, res, product) {
    if (err) {
        console.log("An error ocurred >>>>>>");
        console.log(err);
    } else {
        console.log('Product saved >>>>>>>');
        console.log(product);
    }
});

Here, when I run "node client.js" on the shell What appears is nothing.

I tried to log in my mLab (MongoDB server) and the post data is inserted into the collection.

However, client.post returns neither err or success. It just pauses and eventually leads to socket hang up.

Why is this the case and how do I fix it?

P.S I have tried to set option (agent:false) for clientServer.



via Matt Choi

No comments:

Post a Comment