Search code examples
node.jsexpressurl-routingejs

Get URL value in static page in Express.js


I am beginner to node and express. In my current application the page is displaying using this code :

var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));

and in static folder, there are there files:

css, index and a js file

Listening to 3000 port it is working normally.

But what if I want to access URL like this :

localhost:3000/name=someName

I want to use this name parameter in my js file which is available in static folder.
or suggest any other routing method to do that?


Solution

  • If you want to get the query parameters in your .js file it can be done. So the code would look like this:

    Server (index.js)

    "use strict";
    
    var express = require("express");
    var serveStatic = require('serve-static');
    
    var app = express();
    app.use(serveStatic('static', {'index': ['index.html']}));
    
    app.listen(3000);
    
    console.log("Static express server started");
    

    HTML (/static/index.html)

    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script type="text/javascript" src="test.js"></script>
    </head>
        <body onLoad="readParameters()">
            <div>
                <h3 id="1" >Loading..</h3>
            </div>
         </body>
    </html>
    

    Client side JavaScript (/static/test.js)

    var readParameters = function()
    {
        console.log('Getting parameters..');
        let params = (new URL(location)).searchParams;
        console.log('Query parameters: ', params.toString());
    
        var html = 'Query parameters: ';
        for (let p of params) {
          html += "<br/>" + p.toString();
        }
    
        $("#1").html(html);
    }
    

    Then you can test by entering:

    http://localhost:3000/?test=value
    

    Into your browser.

    You should see:

    Query parameters: test=value
    

    on the index page.

    The code tree should look like this:

    root
    ¦   index.js
    ¦
    +---static
            index.html
            test.js
    

    3 Files:

    /index.js (Node server side code)
    /static/index.html (HTML)
    /static/test.js (Test JavaScript file)