【问题标题】:Using Express and Node to connect HTML, CSS, and Javascript to a server使用 Express 和 Node 将 HTML、CSS 和 Javascript 连接到服务器
【发布时间】:2021-02-26 02:06:51
【问题描述】:

我有 HTML、CSS 和 Javascript 程序可以完美地协同工作。我最近意识到我需要一台服务器才能完成我的一些功能。我使用一些教程创建了一个本地节点服务器。在阅读了一些建议后,我尝试使用 Express 尝试将 HTML、CSS 和 Javascript 添加到节点中,它们都在同一个文件夹中。我拥有的代码(如下)只是导致浏览器继续加载。

const http = require('http');
const fs = require('fs').promises;

const host = 'localhost';
const port = 8000;

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

const requestListener = function (req, res) {
    app.use(express.static(path.join(__dirname, 'public')));
    //res.writeHead(200);
    //res.end("My first server!");
};

const server = http.createServer(requestListener);
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`);
});

【问题讨论】:

    标签: javascript html css node.js express


    【解决方案1】:

    如果您使用的是 express,则不需要 http 模块...

    const express = require('express')
    const app = express()
    
    // '/' is the url you want to host your site
    
    // 'public' is the folder in which you have the necessary frontend files
    
    // and the main html should be named as 'index.html' inside 'public'
    
    app.use('/', express.static('public'))
    
    app.listen(5000, () => console.log('server on port 5000'))
    

    【讨论】:

      【解决方案2】:

      试试这个....

      const express = require('express');
      const app = express();
      const path = require('path');  
      app.use(express.static(path.join(__dirname,'css'));
      app.use('/html',(req,res,next)=>{ 
      res.sendFile(path.join(__dirname,'HTML','text.html');});
      app.listen(3000);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        • 2017-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多