简体   繁体   English

如何使用nodeJs创建Web服务器

[英]How to create web server with nodeJs

I m using following code for creating server with node js but whenever i run local host on this port in browser it always show index.html file. 我正在使用以下代码来创建带有节点js的服务器,但是每当我在浏览器中的此端口上运行本地主机时,它总是显示index.html文件。 What is wrong i do .. 我做错了什么..

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'html'});
    res.end(index);
}).listen(9615);

What you want is to create a router. 您要创建一个路由器。

Check this: http://www.nodebeginner.org/ 检查此: http : //www.nodebeginner.org/

If you come from a php background, you may expect that creating a file on the server makes it accessible throught an url containing its file name. 如果您来自php背景,则可能希望在服务器上创建文件可以通过包含其文件名的url对其进行访问。

In node.js, things work differently. 在node.js中,工作原理有所不同。 You must use a routing system . 必须使用路由系统 Basically, you are going to tell that the "route" (url) views/about is the file about.html. 基本上,您将要知道“ route”(URL)视图/ about是about.html文件。

I think that the best option for you is to install Express framework : it will create basic routes for you, then you'll just have to copy and change some lines to set up new ones. 我认为对您来说最好的选择是安装Express框架:它将为您创建基本路由 ,然后您只需复制和更改一些行即可设置新的行。

Express is also going to make a lot of other stuff easier and faster to develop Express还将使许多其他东西更容易,更快地开发

Have a look at this 5 min Express tutorial 看看这5分钟的Express教程

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

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