gpt4 book ai didi

node.js - 如何创建一个正在运行的API端点?

转载 作者:太空宇宙 更新时间:2023-11-04 00:17:49 25 4
gpt4 key购买 nike

我想知道如何将运行端点设置为 RunKit does .

在 RunKit 的该页面中,它会生成与代码关联的 URL。在浏览器中打开该 URL 将看到代码定义的响应。而且,对代码的更改将实时反射(reflect)。

有人知道他们是如何实现这一目标的吗?

我知道在平均堆栈网站中定义固定的 api。例如,由于以下代码,可以调用 https://myexample.com/api/add/3/5 。但我不知道如何制作一个可以实时改变功能的API。

router.get('/api/add/:a/:b', function (req, res, next) {
var r = Number(req.params.a) + Number(req.params.b);
res.json(r)
})

最佳答案

Express 中间件只是常规的 JS 函数。

为了让路由的功能发生变化,您不需要在运行时更改中间件功能,只需更改它的行为方式即可。

我将尝试在这里演示一个可能的解决方案。
请注意,这只是一个概念验证,而不是生产就绪和/或安全的解决方案。

<小时/>

假设您的网站上有某种在线代码编辑器,它允许您的用户编写 JS 代码并将其保存在您的数据库中。

您可以像这样设置端点路由:

router.get('/endpoint/:id', (req, res) => {
// this id identifies a previously saved code wrote by a user
let id = req.params.id

// NOTE: THIS IS NOT ACTUAL WORKING JS CODE
// fetch the previously saved code from your database as a string
let code = database.getDocumentById(id)

// you can construct an actual JS function form the string, using the `Function()` constructor
let f = Function(code)

// now you can call the function, do whatever you like with it and finally send the user the results
let result = f()
res.send(result)
})

您可能需要为用户提供的代码创建一个包装函数并控制将执行的内容以及结果。

<小时/>

附注
另请查看这篇关于从字符串创建 JS 函数的 SO 帖子:
Is there a way to create a function from a string with javascript?

关于node.js - 如何创建一个正在运行的API端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46019482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com