例如,我想做一个非常简单的web服务器。
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write("Hello!");
res.end();
}).listen(8080);我将这段代码放入WebStorm并运行它。然后,我输入相同的目录index.html文件。
<body>
<button id="btn">Click Me</button>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="requester.js"></script>
</body>我还将requester.js文件放在同一个文件夹中。
$('#btn').on("click", function () {
$.get('/', function () {
console.log('Successful.');
});
});然后在所有文件所在的文件夹中执行命令live。我不知道如何使服务器在本地主机上工作。提前谢谢你。
发布于 2017-09-10 13:31:07
您希望发送您的index.html文件而不是字符串"Hello":
const http = require('http');
const fs = require('fs');
const path = require('path');
http.createServer(function (req, res) {
//NOTE: This assumes your index.html file is in the
// . same location as your root application.
const filePath = path.join(__dirname, 'index.html');
const stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': stat.size
});
var stream = fs.createReadStream(filePath);
stream.pipe(res);
}).listen(8080);根据未来服务器的复杂性,您可能希望研究快递作为内置http模块的替代方案。
https://stackoverflow.com/questions/46141175
复制相似问题