Node中的简单静态HTML服务器 [英] Simple static HTML server in Node

查看:188
本文介绍了Node中的简单静态HTML服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个简单的服务器,以便在开发过程中为本地html和JS文件提供服务。



我尝试获取节点应用程序,网址,并回应网页,但没有运气(这是我的明确尝试)。

 
var fs = require(fs);
var host =127.0.0.1;
var port = 1337;
var express = require(express);

var app = express();
app.use(app.router); //在
下面同时使用根和其他路径app.use(express.static('c:\\\\\ users \\\\\\\\\\\\\\\\\')); //在ROOT /公用文件夹中使用静态文件

app.get(/ *,function(req,res){//根目录
fs.readFile(req.path,函数(err,html){
if(err){
console.log(err);
return;
}
res.write(html);
res.end();
});
});

app.listen(port,host);

但这总是在 c:\ 中查找文件,而不是正确的路径。

我也尝试了一个简单的静态服务器的http-server,但它在服务js文件时总是崩溃。 https://github.com/nodeapps/http-server



我需要能够简单地为您的基本html,css,js文件提供服务,并且希望能够通过URL中提供的任何路径提供服务。这仅仅是为了本地前端开发。
有帮助吗?

解决方案

您应该给 fs.readFile
$ p $ fs.readFile('c:\\\ users \\\\\\\\' \\'+ req.path,function(err,html){

或者您可以做

pre $ code var host =127.0.0.1;
var port = 1337;
var express = require(express);

var app = express();
app.use('/',express.static('c:\\\ users \\ pete \\projects\\'));
app.listen(port,host);


I want to make a simple server so I can serve local html and JS files while developing.

I tried to get a node app to just take whatever is in the URL, and respond with the page, but no luck (here's my attempt with express).

var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use(app.router); //use both root and other routes below
app.use(express.static('c:\\users\\pete\\projects\\')); //use static files in ROOT/public folder

app.get("/*", function(req, res){ //root dir
  fs.readFile(req.path, function(err,html){
    if(err){
        console.log(err);
        return;
    }
    res.write(html);
    res.end();
  });
});

app.listen(port, host);

but this always looks for the file at c:\, not the correct path.

I've also tried http-server for a simple static server, but it is always crashing when serving js files. https://github.com/nodeapps/http-server

I need to be able to serve your basic html,css,js files simply, and hopefully from any path provide in the URL. This is just for local front-end development. Any help?

解决方案

You should give complete path for fs.readFile

fs.readFile('c:\\users\\pete\\projects\\'+req.path, function(err,html){

or you can just do

var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use('/', express.static('c:\\users\\pete\\projects\\'));
app.listen(port, host);

这篇关于Node中的简单静态HTML服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆