node.js 浏览器中输出 “hello world”

前段时间花了几个小时,在command面板输出了“hello world”,今天就来说说怎么在浏览器上输入一个地址,然后页面输出“hello world”。

首先要搭建一个基础的 HTTP 服务器

一般创建一个用于启动应用的主文件 index.js,和一个保存着HTTP服务器代码的模块 server.js。

在项目根目录下创建一个server.js,并写入以下代码:

// 请求(require)Node.js自带的 http 模块,并且把它赋值给 http 变量。
var http = require("http");

// Node.js是基于事件驱动的回调,所以在createServer里面传入一个函数,request对象为接收到的我们需要的所有数据
function start() { // 调用http模块提供的函数: createServer 。 // 这个函数会返回一个对象,这个对象有一个叫做 listen 的方法,这个方法有一个数值参数,指定这个HTTP服务器监听的端口号。 http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888); console.log("Server has started."); } // 提供对外的接口 exports.start = start;

新建一个index.js写入以下代码:

var server = require("./server");

server.start();

在 command 面板执行一下node index.js .然后页面访问 http://127.0.0.1:8888/ ,哈哈,是不是输出 "hello world" 了。

原文地址:https://www.cnblogs.com/qiangspecial/p/3529063.html