使用Node 搭建一个web服务

本文详细介绍如何使用Node.js从零开始搭建一个简易的Web服务,包括创建项目目录、编写服务端代码、添加HTML文件及启动服务的过程。通过具体步骤展示,读者可以快速上手并理解Node.js的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:http://www.runoob.com/nodejs/nodejs-web-module.html

1. 创建node项目目录  /home/data/node/firstNodeApi/ 并跳转到此目录下

# cd /home/data/node/firstNodeApi/

 

2. 创建服务端文件api.js

# vim api.js   --创建并打开api.js文件

按  i  --进入编辑状态,输入以下内容

var http = require('http');
var fs = require('fs');
var url = require('url');

http.createServer(function(request,response){
    var pathname = url.parse(request.url).pathname;
    console.log("Request for "+pathname+"received.");
    fs.readFile(pathname.substr(1),function(err,data){
        if(err){
            console.log(err);
            response.writeHead(404,{'Content-Type':'text/html'});
        }else{
            response.writeHead(200,{'Content-Type':'text/html'});
            response.write(data.toString());
        }
        response.end();
    });
}).listen(8888);
console.log('Server running at http://192.168.96.131:8888');

按 esc 键 退出编辑状态

按  :wq  保存并退出

 

3.添加一个html文件 index.html

# vim index.html    --创建并打开index.html文件

按  i  --进入编辑状态,输入以下内容

<html>
<head>
<meta charset='utf-8'/>
<title>first node</title>
</head>
<body>
<h1>this is first node mode</h1>
<p>这是第一个node项目<p><button onclick="" value="获取百度" />
</body>
</html>

按 esc 键 退出编辑状态

按  :wq  保存并退出

 

4.启动服务

# node /home/data/node/firstNodeApi/api.js

在浏览器输入http://192.168.96.131:8888/index.html  检查是否成功

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值