从零学习node.js之搭建http服务器(二)

2020-06-17 06:06:00易采站长站整理

前言

在上篇文章中我们了解了一下不同模块规范之间的联系与区别。本文我们正式开始node的学习,首先我们从搭建一个http服务器,能运行简单的程序开始说起。

一、hello world

最经典的hello world。首先我们创建一个server.js来保存我们的代码:


console.log( 'hello world' );

在终端输入

node server.js
运行:


node server.js

终端就会输出 hello world 的字样。可是我们一个node服务器程序,总是要在浏览器上访问的呀,这里就要用到node里自带的http模块了:


var http = require('http'); // 引入http模块

// 创建http服务器
// request : 从浏览器带来的请求信息
// response : 从服务器返回给浏览器的信息
http.createServer(function(request, response){
response.writeHead(200, {'content-type': 'text/plain'}); // 设置头部信息,输出text文本
response.write('hello world'); // 输出到页面中的信息
response.end(); // 返回结束
}).listen(3000);
console.log('server has started...');

我们再次在终端输入

node server.js
运行,终端里会有输出
 server has started…
的字样,表示服务器已创建并正在运行,然后我们在浏览器上访问127.0.0.1:3000,就可以看到页面中输出了hello world。

二、form表单

刚才我们只是在页面中输出了一段简单的文本,现在我们要在页面中呈现一个表单,可以让用户输入信息并进行提交:


// server.js
var http = require('http');

http.createServer(function(request, response){
var html = '<html>
<head>
<meta charset=UTF-8" />
</head>
<body>
<form action="/" method="post">
<p>username : <input type="text" name="username" /></p>
<p>password : <input type="password" name="password" /></p>
<p>age : <input type="text" name="age" /></p>
<p><input type="submit" value="submit" name="submit" /></p>
</form>
</body>
</html>';

response.writeHead(200, {'content-type': 'text/html'}); // 输出html头信息
response.write(html); // 将拼接的html字符串输出到页面中
response.end(); // 结束
}).listen(3000);
console.log('server has started...');

修改server.js中的内容,重新运行:


node server.js

刷新页面后,我们发现页面中输出了3个文本框和1个提交按钮。因为我们的程序只是呈现页面,并没有做任何其他的处理,因此在页面中提交数据只是刷新当前页面。