Node.js 入门:创建并运行第一个 HTTP 服务器应用

作者:终端旅客时间:2026-10-22 03:22:24浏览:168

本文介绍如何使用 Node.js 的 http 模块创建一个简单的 Web 服务器。通过 require 引入模块,使用 createServer 方法处理请求,绑定 8000 端口,并在浏览器中访问 localhost:8000 查看输出结果。

Node.js 创建简单应用教程

本节展示如何在 Node.js 环境中构建一个基础的应用程序,供学习者参考实践。

首先,在项目目录下新建一个名为 test.js 的文件。


// require 来载入 http 模块
var http = require('http');
/**
 * 使用 http.createServer() 方法创建服务器,返回 一个对象
 * 对象有一个叫做 listen 的方法,并使用 listen 方法绑定 8000 端口。
 * 函数通过 request, response 参数来接收和响应数据。
 */
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
  if(request.url!=="/favicon.ico"){ //清除第2此访问
    console.log('访问');
    response.write('hello,world');
    response.end('hell,世界');//不写 end() 则没有http协议尾,但写了会产生两次访问
  }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

接下来,在终端中运行该脚本文件。


node test.js

终端输出提示:Server running at http://127.0.0.1:8000/,表明服务器已成功启动。

随后,在浏览器地址栏输入 http://127.0.0.1:8000 进行访问测试。

希望本示例能帮助读者理解 Node.js 程序设计的基本流程。

作者最新文章