[英]node.js calculating sub urls number
i'm very new to node.js, was trying to do as in the example below, but there is a problem with my code that I couldn't figure it out 我是node.js的新手,正尝试按照下面的示例进行操作,但是我的代码存在一个问题,我无法弄清楚
example if 例如
/add/1/1 -> should show in the page 2 / add / 1/1->应该显示在页面2中
/add/2/3 -> should show in the page 5 / add / 2/3->应该显示在第5页中
/sub/1/1 -> should show in the page 0 / sub / 1/1->应该显示在页面0中
/sub/5/2 -> should show in the page 3 / sub / 5/2->应该显示在页面3中
var http = require('http') http.createServer(function(req, res){ var parts = req.url.split("/"), op = parseInt(parts[1]), a = parseInt(parts[2], 10), b = parseInt(parts[3], 10); var result = op ? op(a,b) : "Error"; res.writeHead(200, {'Content-Tybe': 'text/plain'}); res.end("" + result); }).listen(3000, "127.0.0.1");
In your code op
is not a function. 在您的代码中,
op
不是函数。 You must use eval(op)
. 您必须使用
eval(op)
。
The rest of the code (accessing parameters) can be easily done using Express 使用Express可以轻松完成其余代码(访问参数)
const express = require('express')
const app = express()
app.get('/:op/:firstParam/:secondParam', function (req, res) {
var op = req.params.op
var a = parseInt(req.params.firstParam)
var b = parseInt(req.params.secondParam)
var result = eval(op)(a,b)
res.send('result: ' + result)
})
function sum(a, b) {
return a + b
}
function sub(a, b) {
return a - b
}
app.listen(3000)
( Note : this example code will not work if you pass undefiend functions like foo
ie http://localhost:3000/foo/8/2 . Add proper checks when calling eval(op)
based on your specific needs) ( 注意 :如果您传递诸如
foo
这样的undefiend函数(例如http:// localhost:3000 / foo / 8/2,则此示例代码将不起作用。根据您的特定需求在调用eval(op)
时添加适当的检查))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.