因此,我有一个文件,我想从我的计算机托管,我希望能够在端口监听出于各种原因。我正在使用
const port = [number]
http.createServer((req, res) => {
let responseCode = 404;
let content = '404 Error';
const urlObj = url.parse(req.url, true);
if (urlObj.query.code) {
const accessCode = urlObj.query.code;
}
if (urlObj.pathname === '/') {
responseCode = 200;
content = fs.readFileSync('./index.html');
}
res.writeHead(responseCode, {
'content-type': 'text/html;charset=utf-8',
});
res.write(content);
res.end();
})
.listen(port);
所有这些好东西都让我可以拥有一个本地文件,http://localhost:[number]
。然而,我不太确定如何使用同样的方法在一个在线网站上托管,在这个网站上,我将我的代码上传到网站,然后从我的计算机上启动网站(使用创建服务器)。有没有人知道如何创建一个不是私有/本地的服务器,而是一个公共的服务器(是的,我可以使用web主机)。
发布于 2020-10-09 19:48:37
我推荐使用express框架,因为它极大地简化了静态文件的服务。它就像下面这样简单:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static(__dirname + '/public'));
app.listen(port , () => {
console.log(`Server is running at port ${port}`);
});
有了上面的代码,剩下的工作就是在你的应用程序目录中创建一个名为public
的文件夹,用来放置你的html/css/js
文件。
https://stackoverflow.com/questions/64279382
复制相似问题