简体   繁体   中英

Node.JS run Sandbox in REST service

I am using Node Restify Module to create a REST service that accepts POST. Within the service I am trying to create a Sandboxed process using Node Sandbox module because we will be running dynamically inserted Javascript and if something goes wrong, I dont want it to affect the main Node instance.

When I try to create the Sandbox, something goes wrong and causes the REST service to come back empty.

Here is my code

    var restify = require('restify');
var Sandbox = require("sandbox");
var logic;

function createSandbox(body) {
    var s = new Sandbox();
    s.run("1 + 1", function(output) {
        logic = body.names + " has " + output.result;
    });
}

function respond(req, res, next) {
    createSandbox(req.body);
    res.send(logic);
}
var server = restify.createServer();
server.use(restify.bodyParser({
    mapParams: false
}));
server.post('/hello/:name', respond);
server.head('/hello/:name', respond);

server.listen(8080, function() {
    console.log('%s listening at %s', server.name, server.url);
});

In my http request I have {"names":"rob"} in the body

I am expecting the following response

rob has 2

------------UPDATE------------------- This works

var restify = require('restify');
var Sandbox = require("sandbox");
var logic;

function respond(req, res, next) {
   var s = new Sandbox();
    s.run("1 + 1", function(output) {
        logic = req.body.names + " has " + output.result;
        res.send(logic);
    });  
}
var server = restify.createServer();
server.use(restify.bodyParser({
    mapParams: false
}));
server.post('/run/:id', respond);
server.head('/run/:id', respond);

server.listen(8080, function() {
    console.log('%s listening at %s', server.name, server.url);
});

Sandbox.run() is asyncronous. It just sets the sandbox up to run at a later time and returns immediately before the code it sandboxes is actually run, so you're reading logic before it's set.

A quick demo;

var Sandbox = require("sandbox");

function createSandbox() {
    var s = new Sandbox();
    s.run("1 + 1", function(output) {
        console.log("inside");
    });
}

createSandbox();
console.log("outside");

> outside
> inside

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM