gpt4 book ai didi

javascript - Response.write() 不返回值

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:53 24 4
gpt4 key购买 nike

我一直在关注this tutorial有关 Nodejs 的介绍,但我在使用 response.write() 返回某些内容时遇到问题。

当我转到domain:8001时,我的server.js代码可以正常返回“hello world”,但导航到domain:8001/socket.html会返回空白屏幕。

我使用console.log来检查写入“socket is here”的代码。正在执行,但我不确定为什么它没有做任何事情。

服务器.js:

var http = require("http");
var url = require('url');
var fs = require('fs');

var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
console.log(__dirname);
console.log(path);

switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});

response.write("socket is here.");
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}

response.end();
});

server.listen(8001);

var io = require('socket.io').listen(server);

socket.html:(尽管其中包含的内容并不重要)

<html>
<head>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect();
</script>
<div>This is our socket.html file</div>
</body>
</html>

最佳答案

您将在等待 fs.readFile() 完成之前结束响应。试试这个:

var http = require("http");
var url = require('url');
var fs = require('fs');

var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
console.log(__dirname);
console.log(path);

switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});

response.write("socket is here.");
}
response.end();
});
return;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}

response.end();
});

server.listen(8001);

var io = require('socket.io').listen(server);

此外,执行 fs.readFile(__dirname + path, ...); 可能存在危险,因为有人可能会发送类似 /../../../../../../etc/passwd 的请求。您应该做的是使用 path 模块将 __dirname + path 解析/规范化为绝对路径,然后确保该绝对路径以公共(public)目录的绝对路径开头。

关于javascript - Response.write() 不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24854655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com