繁体   English   中英

如何使用服务器运行index.html(针对angularjs和其他框架)

[英]How to run index.html using a server(for angularjs and other frameworks)

我搜索了stackoverflow和一些论坛,找不到直接的解决方案,后来我遇到了一些可以正常工作的ans,所以我将其发布在这里:)

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

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

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

方法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中投放


方法2:

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

并且您的index.html文件将在localhost:8000中提供

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM