javascript - 为什么我的 res.sendFile() 将 html 发送到浏览器控制台而不是呈现新的 html 页面?
问题描述
我正在通过一个应该具有以下顺序的练习来练习服务器请求(使用 express JS | v. 4.17.1):
单击按钮:发送服务器请求(使用 jQuery $.get):从 routes.js 页面发送 res 文件
问题是 routesJS 页面确实发送了响应,但响应显示在浏览器的控制台中。这是带有一些解释的代码片段
- 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>
- 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"));
});
};
解决方案
来自您的 Javascript 的 Ajax 请求从服务器获取内容,并将该内容返回给您的 Javascript。
浏览器页面与该内容无关(除了托管您的 Javascript)。如果您希望将获取的内容插入到当前网页中,那么您必须在获取后使用您的 Javascript 自己将其插入。
另一方面,如果您只想在浏览器中转到新页面,那么不要使用 Ajax 调用来获取内容,只需设置window.location
为该新 URL,然后浏览器就会获取内容,更新 URL 栏并在浏览器窗口中显示获取的内容。
window.location = "/clicked";
推荐阅读
- javascript - SpeechSynthesisInstance.pause 在 Firefox 上不起作用?
- postgresql - 为什么 NEW.name 返回 NULL?PostgreSQL 11
- javascript - 使用 puppeteer 获取元素和文本列表
- python - 没有名为错误的模块。如何从不同目录的 python 中的 .pyx 文件导入函数?
- jquery-ui - Jquery Autocomplete 错误 menuselect 和 menufocus 无法读取未定义的属性值
- ios - iOS 使用 Agora 语音通话加入和离开频道时状态栏显示为红色
- php - 在php中进行求和时如何处理空值
- python - Runtime.ImportModuleError:无法导入模块“lambda_function”:没有名为“httplib2”的模块
- laravel - 如何在laravel中显示具有yajra数据表多对多关系的数据?
- hadoop - 为什么 cloudera 5.12 vm 中的默认复制因子为 1,而在以前的版本中为 3?