首页 > 解决方案 > 为什么我的 res.sendFile() 将 html 发送到浏览器控制台而不是呈现新的 html 页面?

问题描述

我正在通过一个应该具有以下顺序的练习来练习服务器请求(使用 express JS | v. 4.17.1):

单击按钮:发送服务器请求(使用 jQuery $.get):从 routes.js 页面发送 res 文件

问题是 routesJS 页面确实发送了响应,但响应显示在浏览器的控制台中。这是带有一些解释的代码片段

  1. html 页面包含 |button| 以及发起请求的脚本
<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. routesJS 页面需要以下包
    -- path >> 这用于使用 res.sendFile() 获取整个路径
    -- http >> 这是在 youtube ref 的方法中引入的
    -- fs >> 这是在来自 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"));
    });

};

标签: javascripthtmlexpressrequestresponse

解决方案


来自您的 Javascript 的 Ajax 请求从服务器获取内容,并将该内容返回给您的 Javascript。

浏览器页面与该内容无关(除了托管您的 Javascript)。如果您希望将获取的内容插入到当前网页中,那么您必须在获取后使用您的 Javascript 自己将其插入。

另一方面,如果您只想在浏览器中转到新页面,那么不要使用 Ajax 调用来获取内容,只需设置window.location为该新 URL,然后浏览器就会获取内容,更新 URL 栏并在浏览器窗口中显示获取的内容。

window.location = "/clicked";

推荐阅读