0

I followed the tutorial here to run PowerShell commands via Node.JS and it worked fine: https://www.jeansnyman.com/posts/executing-powershell-commands-in-a-nodejs-api/

I then tried adding a route at localhost:5000/mypage, as seen below. However, when I navigate to localhost:5000/mypage, it executes the command for the / route (i.e., makes a MyFolder1 directory), as if I navigated to localhost:5000/. How can I successfully configure the localhost:5000/mypage route?

    //Imports
    const express = require('express')
    const Shell = require('node-powershell')
    
    //Initialize PowerShell
    const ps = new Shell({
        executionPolicy: 'Bypass',
        noProfile: true
    });
    
    //Setup and configure app
    const app = express()
    const port = 5000
    
    //Route request
    app.use('/', (req, res) => {
        ps.addCommand(`mkdir \\\\NetworkDrive\\MyFolder1`);
        ps.invoke()
            .then(response => {
                res.send(response)
            })
            .catch(err => {
                res.json(err)
            });
    });
    
    app.use('/mypage', (req, res) => {
        ps.addCommand(`mkdir \\\\NetworkDrive\\MyFolder2`);
        ps.invoke()
            .then(response => {
                res.send(response)
            })
            .catch(err => {
                res.json(err)
            });
    });
    
    
    //Initialize app
    app.listen(port, () => console.log(`Server listening on port ${port}!`))```
O. Jones
  • 103,626
  • 17
  • 118
  • 172
velkoon
  • 871
  • 3
  • 15
  • 35
  • 3
    Does this answer your question? [Order of router precedence in express.js](https://stackoverflow.com/questions/32603818/order-of-router-precedence-in-express-js) Put `app.use('/mypage'.,..)` before `app.use('/',...)` in your program. – O. Jones May 12 '21 at 21:22
  • @O.Jones - You know, I had that exact thought and didn't try it, thinking it'd be a waste of my "precious" 5 seconds, haha. It also seems less intuitive to precede the root route with child routes. Thank you! – velkoon May 12 '21 at 21:53

0 Answers0