解决 Node.js Express 服务器路由问题

问题描述 投票:0回答:1

我在 NodeJS 中尝试了这个简单的代码:

const express=require("express");

const app=express();

const accounts=[]

app.use("/dashboard",function(req,res,next){
    res.send(accounts);
    next();
})

app.post("/dashboard/add-account/:address{6}",function(req,res,next){
    accounts.push(req.params.address);
    console.info(accounts);
    next();
})

app.put("/modify-account/:index/:address{6}",function(req,res){
    accounts[req.params.index]=req.params.address;
    res.send(accounts);
})

app.delete("/dashboard/delete-account/:index[0-9]",function(req,res){
    accounts[req.params.index]="";
    console.info(accounts);
})

app.listen(3001,"127.0.0.1",650,()=>{console.info("Server is ready ...")});

通过发送此请求:

http://localhost:3001/dashboard/add-account/0x1234

但是控制台上没有任何记录! 这段代码是学习 ExpressJS 的简单代码,我对路由和中间件功能很陌生。我该怎么办?

node.js express url-routing
1个回答
0
投票

您没有指定您尝试向

http://localhost:3001/dashboard/add-account/0x1234
提出什么类型的请求。如果它是 GET 请求(即来自浏览器),您将不会看到任何记录,因为您没有 GET 路由处理程序。

尝试添加类似以下内容来开始:

app.get("/dashboard/add-account/:address{6}",function(req,res,next){
    console.info("TODO: render add account form or similar here.");
    next();
})
© www.soinside.com 2019 - 2024. All rights reserved.