【问题标题】:How to run index.html using a server(for angularjs and other frameworks)如何使用服务器运行 index.html(对于 angularjs 和其他框架)
【发布时间】:2018-10-08 03:45:21
【问题描述】:

我已经搜索了 stackoverflow 和一些论坛,但找不到直接的解决方案,后来我遇到了一些运行良好的答案,所以我将其发布在这里:)

ans 用于以下文件夹结构,您也可以根据自己的文件夹结构自定义它。

--project
---app
----js
----services
----(...)
----index.html

请参考下面的答案。 如果您有更好的方法,请发布,您也可以添加一些 cmets 以使答案更好。 谢谢。

【问题讨论】:

    标签: angularjs node.js npm httpserver


    【解决方案1】:

    方法一:

    使用 node.js 运行 index.html 文件,将以下代码复制粘贴到应用文件夹中的 server.js 文件(层次结构之上)

    var http = require('http');
    var fs = require("fs");
    
    http.createServer(function(request, response) {
      if(/(.*?).css$/.test(request.url.toString())){
         sendFileContent(response, request.url.toString().substring(1), "text/css");
      }else if(/(.*?).js$/.test(request.url.toString())){
        sendFileContent(response, request.url.toString().substring(1), "text/javascript");
      }else if(/(.*?).html$/.test(request.url.toString())){
        sendFileContent(response, request.url.toString().substring(1), "text/html");
      }else if(request.url.toString().substring(1) == ''){
        sendFileContent(response, "index.html", "text/html");
      }
    }).listen(3000);
    
    function sendFileContent(response, fileName, contentType){
      fs.readFile(fileName, function(err, data){
        if(err){
          response.writeHead(404);
          response.write("Not Found!");
        }
        else{
          response.writeHead(200, {'Content-Type': contentType});
          response.write(data);
        }
        response.end();
      });
    }
    

    然后从 app 文件夹运行 node server.js。 您的 html 文件将在 localhost:3000 中提供


    方法二:

    使用 http-server。按照此link 中的步骤全局安装 http-server 并从您的应用程序文件夹运行 cmd http-server -a localhost -p 8000 -c-1 ./app

    您的 index.html 文件将在 localhost:8000 中提供服务

    注意:上述方法中.listen和-p中的端口号可以更改。

    【讨论】:

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