Man*_*rma 2 javascript node.js express
我正在学习节点和Express,我想在Express Example中重复一个单词
用户访问...... / repeat / hello / 5我希望“ hello”在浏览器页面上打印5次,
如果他们这样做/ repeat / hello / 3,我希望“ hello”打印3次。我怎样才能做到这一点?如果可以的话,我可以使用for循环嵌套吗?
这是我的代码
var express = require("express");
var app = express();
//const repeating = require("repeating");
app.get("/", function(req,res){
res.send("Hi there, welcome to my Assignment!");
});
//pig
app.get("/speak/pig", function(req,res){
res.send("The pig says Oink");
});
//cow
app.get("/speak/cow", function(req,res){
res.send("The cow says Moo");
});
//dog
app.get("/speak/dog", function(req,res){
res.send("The dog says Woof, Woof!");
});
app.get("/repeat/hello/:3", function(req,res
res.send("hello, hello, hello");
});
app.get("/repeat/blah/:2", function(req,res){
res.send("blah, blah");
});
app.get("*", function(req,res){
res.send("Sorry, page not found... What are you doing with your life?")
});
app.listen(3000, function(){
console.log('Server listening on Port 3000');
});
Run Code Online (Sandbox Code Playgroud)
您可以使用req.params
访问URL参数。您还可以参数化要重复的单词:
app.get("/repeat/:word/:times", function(req,res){
const { word, times } = req.params;
res.send(word.repeat(times));
});
Run Code Online (Sandbox Code Playgroud)
这样,您可以摆脱/repeat/hello
和/repeat/blah
端点,并且只有一个通用端点可以处理所有单词和所有数字
如果要使用分隔符,则可以创建一个临时数组并将其连接,如下所示:
const result = (new Array(+times)).fill(word).join(',');
res.send(result);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
67 次 |
最近记录: |