1

I'm practicing server requests (using express JS | v. 4.17.1) through an exercise that is supposed to have the following sequence:

click button : send server request (using jQuery $.get) : send res file from routes.js page

The issue is that the routesJS page DOES send a response, but the response shows up in the console of browser instead. Here are snippets of code with some explanation

  1. The html page contains the |button| and the script for initiating the request
<script>
    $("#go").on("click", function(event){
        //no flickering*
        event.preventDefault();

        //get the page
        $.get("/clicked", ' ', function(res){
            //lets user know the click was received
            alert("getting page along clicked path");

            //prove that the server has a response
            console.log("server response with:\n\n" + res);
        });

    });
</script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Button</title>
</head>
<body>
    <p>The Button</p>
    <button id="go">Click Me</button>
</body>
</html>
  1. the routesJS page requires the following packages
    -- path >> this was used to get the whole path using a res.sendFile()
    -- http >> this was introduced in a method from youtube ref
    -- fs >> this was introduced in a method from youtube ref
//inside routesJS page
var path = require("path");
var http = require("http"); //introduced in youtube ref
var fs = require("fs");     //introduced in youtube ref

//youtube ref
//https://www.youtube.com/watch?v=p5eCYKiZN-4

module.exports = function (app) {

    /** 01) original index page-retrieval method
      * uses 'path'
      * delivers main page before a button click
      * ----------------------------------------
    
    app.get("/", function(req, res) {
      res.sendFile(path.join(__dirname, "/../public/index.html"))
    });
    
    ***/
    
    
    /** 02) original response page retrieval method
      * uses 'path'
      * returns the second page after button clicks
      * -------------------------------------------
    
    app.get("/clicked", function (req, res) {
      res.sendFile(path.join(__dirname, "/../public/click.html");)
    }
    
    ***/

    /** 03) this is from the youtube reference above
      * intended to take the place of (02) if it works
      * uses 'path' to join; (03) is currently active*/

    app.get("/clicked", function (req, res) {

        console.log("\n..page button was clicked; checking fs..");
        
        //turn joined paths into variables; test necessity of path
        //---------------------------------------------------------

        var path1 = path.join(__dirname, "/../public/click.html");
        var path2 = "./app/public/click.html";

        //re-tries method (02) > to no avail
        //----------------------------------
        //res.sendFile(path1);

        //passes a url, a null, and a callback to fs.readfile
        //---------------------------------------------------

        fs.readFile (path2, null, function(error, data) {

            if (error) {

                //in the event of an error
                //------------------------

                res.writeHead(404);
                res.write("...we have not seen that file!");
                console.log("error occurred during fs read");
            
            } else {

                //in the event of a successful read, 3x ways tried to send data

                //Option.3A: defines writeHead and writes the <html> as data
                //remember to write writeHead vs writehead (capitalization matters)
                //-----------------------------------------------------------------

                //res.writeHead(200, {'Content-Type' : 'text/html'});
                //res.write("..your file was successfully read...");
                //res.write(data);

                //Option.3B: sets the status, defines content type, sends data
                //------------------------------------------------------------

                //res.sendStatus(200);
                //res.set("Content-Type", "text/html");
                //res.write(data);

                //Option.3C: defines requirement type as 'html'
                //use the res.format() per expressjs.com below
                //expressjs.com/en/4x/api.html#res.format
                //---------------------------------------

                req.accepts("html");
                res.format({

                    html: function () {
                        console.log("sending data through html format");
                        res.send(data)
                    },

                    default: function() {
                        //log the request and respond with 406
                        res.status(406).send("not acceptable") 
                    }
                });

                console.log("..the fs read was successful; check the browser");
                console.log("..the writeHead has been written..");
            
            }
            console.log("..ending..");
            res.end();

        }); //closes fs.readFile

    }); //closes app.get "clicked"

    // If no matching route is found, the default to home
    app.use(function (req, res) {
        res.sendFile(path.join(__dirname, "/../public/index.html"));
    });

};
Arthur L.
  • 17
  • 6

1 Answers1

0

Ajax requests from your Javascript fetch content from a server and that content is returned back to your Javascript.

The browser page has nothing to do with that content (other than hosting your Javascript). If you want the fetched content to be inserted into the current web page, then you have to insert it yourself with your Javascript after fetching it.

If, on the other hand, all you want to do is to go to a new page in the browser, then instead of using an Ajax call to fetch the content, just set window.location to that new URL and then the browser will fetch the content, update the URL bar and show the fetched content in the browser window.

window.location = "/clicked";
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks for the response! So, I didn't want to over-explain what was going on here (because it felt like a lot was going on already), but my goal is to be intentional about using jQuery in the html to get the page...even if other ways (like hyperlinking) might work
    In your response, you mentioned that the I have to insert the retrieved data with the javascript. The javascript between the < script > tags do retrieve the data in the form of text, but it's plain text Is there some code that I need to add to the html-side js to make the page render? Or does the res.sendFile do it?
    – Arthur L. Jun 21 '20 at 23:53
  • @ArthurL. - I'm not sure you follow yet. Whatever your server sends back to the your Ajax call will be received by your Javascript. If you want that content to show in the page, then you must insert it into the page with your Javascript when it receives that content back from the Ajax call. Ajax calls do not affect the current page display on their own. If you want HTML send back to the Ajax call, then just make sure your server sends HTML. Whatever it sends is what the Ajax call receives. – jfriend00 Jun 22 '20 at 00:05
  • @ArthurL. - If you got back from your server a chunk of HTML, you could replace the current page's contents with that HTML by doing this in your Ajax response handler: `document.body.innerHTML = myHTML;`. If you want to insert it into some particular location in the page without replacing all the current contents, then you need to use various jQuery methods to find the insertion point and then insert it using an appropriate jQuery method. This is one of the things jQuery is often used for. – jfriend00 Jun 22 '20 at 00:07
  • Thanks for taking the time to explain (and being patient with a newbie). The part of your explanation that makes the most sense is that if I want HTML sent back to the AJAX, then I need to make sure the server sends HTML...that will point me back to the res.format() as defined in the express documentation. I'll replace the code with your original suggestion as well >> a broad swatch of working methods is what I'm after here – Arthur L. Jun 22 '20 at 00:21
  • @ArthurL. - You don't need `res.format()`. If you have a file containing HTML and that file has an `.htm`, or `.html` file extension, then `res.sendFile()` will send that HTML just fine and it will get sent with the HTML content type. Mostly, you just need to write the correct client-side code to do something with the HTML you receive other than show it in the console. – jfriend00 Jun 22 '20 at 00:26
  • `window.location` works flawlessly. I'll admit that it does not solve the issue the way that I thought it would because I still have questions about what was happening with res variables over on the server file, but in terms of getting the ultimate result: it works. I plan on opening up a new question about the differences between the methods used/discussed in this scenario – Arthur L. Jun 22 '20 at 02:47