gpt4 book ai didi

javascript - 我怎样才能在端口 80 上使用 node.js 提供单页 html?

转载 作者:行者123 更新时间:2023-11-30 17:02:38 24 4
gpt4 key购买 nike

我的项目结构是这样的:

  • 项目
    • Assets /图片/
    • css/application.css
    • js/application.js
    • 字体
    • Node 模块
    • index.html
    • server.js
    • package.json

我的目标是能够在项目文件夹中运行“node server.js”并让它在端口 80 上服务。转到 localhost:80 或 w.e 将渲染 index.html 及其 css/assets/js .

我尝试过使用 connect、express 和 http,但没有成功……刚接触 node。

谢谢!

最佳答案


首先,改变你的结构:

  • 项目
    • Assets /图像/
    • assets/css/application.css
    • Assets /js/application.js
    • Assets /字体
    • Node 模块
    • views/index.html
    • server.js
    • package.json

首先需要一些包:

var express = require('express'),
app = express(),
path = require('path');

它们在终端窗口中运行:

npm install express

他们设置配置:

app.set('views', path.join(__dirname, 'views')); // This is to serve static files like html in the views folder
app.set('view engine', html); // your engine, you can use html, jade, ejs, vash, etc
app.set('port', process.env.PORT || 80); // set up the port to be production or 80.
app.set('env', process.env.NODE_ENV || 'development');

app.use(express.static(path.join(__dirname, 'assets'))); // // This is to serve static files like .css and .js, images, fonts in the assets folder

他们创建你的路线:

app.get('/', function(req, res) {
res.send('Hello word');
});

app.get('/something', function(req, res) {
res.send('Hei, this is something!!!');
});

如果你想渲染索引,在 views 文件夹中:

app.get('/index', function(req, res) {
res.render('index');
});

最后:

app.listen(app.get('port'), function(req, res) {
console.log('Server listening at ' + app.get('port')');
});

他们访问 localhost:80/index

关于javascript - 我怎样才能在端口 80 上使用 node.js 提供单页 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28565525/

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