将前端的值传递给后端,而不使用url

我有一个平均堆栈应用程序。 在后端,我有api.js

 var express = require('express') var router = express.Router(); var body = 'response.send("hello fixed")'; var F = new Function ("request", "response", body); router.get('/api/special', F); module.exports = router; 

因此,在浏览器中https://localhost:3000/api/special返回hello fixed

现在,我想让前端定义body的内容。 例如,我可以在网页上制作一个textarea,用户可以随意input例如response.send("hello flexible") 。 然后,我需要将这些内容传递给nodejs,以便https://localhost:3000/api/special现在返回hello flexible

有谁知道如何做到这一点?

编辑1:继李安李的评论,我修改了api.js

 var express = require('express') var router = express.Router(); router.put('/endpoint', function (req, res, next) { console.log("api.js router.put /endpoint"); router.get('/api/special', eval('(' + req.body.value + ')')) }) module.exports = router; 

而在控制器中:

 app.controller('EndpointCtrl', ['$scope', '$http', function ($scope, $http) { $scope.body = 'function (request, response) { response.send("Hello") }'; $scope.changeBody = function (body) { return $http.put('/endpoint', { value: body }) } }]) 

奇怪的是,当我put /endpoint只有第一次,而后来put似乎并没有更新/api/special 。 有谁知道为什么?

另外,在后台的控制台上看到第二个或第三个put /endpoint需要花费几秒钟的时间。

为了扩大我的评论,这里是一个与你的例子相同的解决scheme,而是使用调用variables的中间件。

 const express = require( "express" ); const app = express(); function rawBody( req, res, next ) { req.setEncoding( "utf8" ); req.body = ""; req.on( "data", chunk => req.body += chunk ); req.on( "end", next ); } app.use( rawBody ); const router = express.Router(); // f is our variable; we initialize it to just call next, likely resulting in a 404 let f = ( req, res, next ) => next(); // use an intermediary function to invoke f // don't use just f, which is passed by value and wouldn't update router.get( "/api/special", ( ...args ) => f( ...args ) ); router.put( "/endpoint", ( req, res ) => { // update f f = eval( "(" + req.body + ")" ); // send a response; otherwise the request will hang res.sendStatus( 200 ); } ); app.use( router ); app.listen( 3000 ); 

展开运算符(…)以两种方式工作:将函数参数集合到数组中或将数组展开为参数。 对于节点LTS或更高版本,这是有效的语法。 你也可以明确地使用( req, res )

我必须强调,这样一个端点是非常脆弱的,因为它可以使用require,从中可以做任何有权限的进程(如下载和安装软件)。 vm2是一个npm模块,可能有帮助,但是它们不提供实际的安全保证。 我build议你在沙盒中执行代码,只允许沙箱有限的权限(比如不能访问文件系统或networking)。