Search code examples
node.jsexpressurl-routing

Troubleshooting Node.js Express Server Routing Issue


I tried this simple code in 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 ...")});

By sending this request: http://localhost:3001/dashboard/add-account/0x1234

But nothing logged on the console! this code is a simple code to learn ExpressJS and I am new to routing and middleware functions. What should I do?


Solution

  • You didn't specify what type of request you're attempting to make to http://localhost:3001/dashboard/add-account/0x1234. If it's a GET request (i.e. from a browser), you wouldn't see anything logged because you don't have a GET route handler.

    Try adding something like the following to get started:

    app.get("/dashboard/add-account/:address{6}",function(req,res,next){
        console.info("TODO: render add account form or similar here.");
        next();
    })