【问题标题】:Using .createServer to make a public website使用 .createServer 制作公共网站
【发布时间】:2021-01-24 11:54:16
【问题描述】:

所以我有一个文件要从我的计算机托管,并且出于各种原因我希望能够在端口上监听。我正在使用


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]。但是,我不确定如何使用相同的方法在在线网站上进行托管,在这种方法中,我将代码上传到网站,然后让网站从我的计算机启动(使用创建服务器)。有谁知道如何基本上创建一个不是私有/本地的服务器,而是公共的(是的,我可以使用网络主机)。

【问题讨论】:

  • 什么?!这是一个编码问题还是“如何”将服务器“发布”到 interweebz ?

标签: node.js json hosting


【解决方案1】:

我推荐使用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 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多