开发一个服务器端程序

发表于 2020-05-09 11:50:44
阅读 28

介绍

介绍

今天我们就开发第一个 nodejs 项目,一个简单的 http server 服务器端程序

教程

准备

创建项目 DemoV1 的目录,并进入

mkdir DemoV1
cd DemoV1

通过 npm 初始化项目

[root@tongfunet DemoV1]# npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (demov1) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /data/docker.data/tfhome/SDPHP/Projects/NodeJS/DemoV1/package.json:

{
  "name": "demov1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes)

导入 http 模块

npm install http -g

编写服务器端

建立 index.js

建立 main 指定的脚本 index.js,写入下面的代码

const httpLib = require('http');
const urlLib = require('url');
const querystringLib = require('querystring');
const server = httpLib.createServer(function(req, res){
    var requestData = '';
    
    req.on('data', function(data){
        requestData += data;
    });
    req.on('end', function(){
        var $_SERVER = {}, p, tp, $_GET, $_POST, responseData, length;

        // make $_SERVER, $_GET, $_POST
        urlObj = urlLib.parse(req.url, true);
        $_SERVER.REQUEST_METHOD = req.method;
        $_SERVER.REQUEST_URI = req.url;
        for(p in req.headers){
            tp = p;
            if(p == "host" || p == "user-agent"){
                tp = "http-"+ p;
            }
            tp = tp.replace( /\-/g , "_");
            $_SERVER[tp.toUpperCase()] = req.headers[p];
        }
        $_GET = urlObj.query;
        $_POST = querystringLib.parse(requestData);
        
        // dump
        console.log($_SERVER);

        // make response
        responseData = "hello world !";
        if($_SERVER.REQUEST_METHOD == "POST"){
            if(requestData == ""){
                responseData += " there is no post data.";
            }
            else{
                responseData += " the post data is '"+ requestData+ "'.";
            }   
        }
        length = responseData.length;
        
        // reponse
        res.writeHead(200, {
           "Content-Type":"text/html",
           "Content-Length":length,
           "Connection":"close"
        });
        res.write(responseData);
    });
});
server.listen(8080);

启动服务器端

通过 node 启动服务器端

node index.js

测试服务器端

通过 curl 测试

curl -d 'a=b&c=d' 'http://localhost:8080/path?a1=b1&c1=d1'

可以看到服务器端的输出内容

{
  REQUEST_METHOD: 'POST',
  REQUEST_URI: '/path?a1=b1&c1=d1',
  HTTP_USER_AGENT: 'curl/7.29.0',
  HTTP_HOST: 'localhost:6789',
  ACCEPT: '*/*',
  CONTENT_LENGTH: '7',
  CONTENT_TYPE: 'application/x-www-form-urlencoded'
}

设置项目

设置项目脚本

打开 package.json,在 scripts 里面增加一行

"scripts": {
  "test": "node index.js"
}

使用项目脚本

通过 npm 启动服务器端

npm test

可以看到服务器端已经启动起来了

> demov1@1.0.0 test /tongfu.net/web/NodeJS/DemoV1
> node index.js


鬼谷子叔叔

跟福哥学编程吧~~
日志
212
浏览
1626