是否可以将功能从服务器发送到客户端?

时间:2019-05-28 17:25:46

标签: node.js

根据我对NodeJS / Javascript如何工作的了解,我相信这是有可能的。是吗?

我希望能够基于http请求向客户端发送函数,如下所示(伪短代码):

// Server
server.get("/function",()=>{
   return function () => {
     console.log('test)
}

// client
request ("server/function",(res)=>{
     func = res.body
     func()
// # result
// test   

我试图转换为字符串以从服务器发送函数并转换回客户端上的对象,但是它返回的错误我无法理解,为什么我好像发送一个简单的键值json对象一样有效

// server
const http = require('http');
const port = 3000;
const hostname = '127.0.0.1';

const server = http.createServer((req, res) => {
    if (req.url === '/function') {
        res.statusCode = 200;
        function func () {
            console.log('test')
        }
        res.end(func.toString())
    }
});

server.listen(3000)
// client
const http = require('http');

const httpGet = url => {
    return new Promise((resolve, reject) => {
        http.get(url, res => {
            res.setEncoding('utf8');
            let body = '';
            res.on('data', chunk => body += chunk);
            res.on('end', () => resolve(body));
        }).on('error', reject);
    });
};

const call = async () => {
    const body = await httpGet('http://localhost:3000/function')
    console.log(`${body}`)
    func = JSON.parse(body) // try to redefine function based on the response
}

const func = () => {
    console.log('before')
}
func() // run the func defined here

call()

func() // run the function got from the request?

这个想法是让一个客户端能够执行几乎任何代码,而无需更新客户端本身。

2 个答案:

答案 0 :(得分:1)

我不确定您为什么要这样做,这确实不安全,并且您不应该具有执行此操作的Web应用程序。但是这里:

假设您有一个功能:

await _auth.signInWithEmailAndPassword(email: email, password: password);

并作为字符串:

function test() {
  console.log("test")
}

您需要首先获取函数主体:

const funcString = test.toString()
// ^ is now "function test() {\n  console.log(\"test\")\n }"

然后从中创建一个函数:

const funcBody = funcString.replace(/^[^{]+{/, '').replace(/}[^}]*$/, '')
// ^ is now "console.log(\"test\")"

现在,如果您拨打const newTest = Function(funcBody) ,您将在控制台中看到newTest()的打印内容。

请注意,我用来获取函数主体的正则表达式不适用于所有函数。例如,对于test,您将需要其他正则表达式。

答案 1 :(得分:0)

我不确定这是最好的主意。

从历史上看,您描述的客户端与服务器之间的关系是通过remote procedure calls反转的,其中客户端将调用远程服务器上的特定端点。听起来,使客户端任意执行代码的最大吸引力在于,无需更新客户端代码。如果要对服务器代码进行向后不兼容的更改会怎样?我认为使用版本化的API终结点基于客户端逻辑在服务器端执行代码会取得更好的成功,您会在npm内找到许多RPC和/或REST框架。

  

想法是让一个客户端能够执行几乎任何代码,而无需更新客户端本身。

最后要记住的一件事是安全性。如果我找到您的客户端并替换了我的恶意JavaScript,该怎么办?

相关问题