node.js使用express發(fā)布REST API service例子

使用express發(fā)布REST API service的例子。
并通過curl/python/node.js客戶端分別發(fā)送請(qǐng)求。

1. node.js server 端

接收client發(fā)出的POST請(qǐng)求

var sleep = require('sleep');
var express = require('express');
var bodyParser = require('body-parser');

var port = 8080
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/service/pushservice/api/v1/usage', api_push);
app.post('/service/{servicename}/api/v1/usage',     api_push);

app.listen(port, '0.0.0.0',  function() { console.log('Server started on %d', port); })

function api_push(req, res) {
    console.log("===================================");
    // console.log("query: " + JSON.stringify(req.query, null, 4));
    // console.log("body : " + JSON.stringify(req.body, null, 4));

    // Get query parameter
    var pushId = req.query.pushId;
    console.log("pushId: " + pushId);

    // Get path parameter
    var servicename = req.params.servicename;
    console.log("servicename: " + servicename);

    // Get body parameter if body is a json map
    var accountId = req.body.accountId;
    var timestamp = req.body.timestamp;
    console.log("servicename: " + servicename);

    // Response
    res.status(200).end()
    // res.status(202).send({"result": "accept"});
    // res.status(400).send({
    //    "errorCode"     : "ERR1001",
    //    "errorMessage"  : "I meet a problem, thanks"
    // })

2. 客戶端 - curl

$ curl -v -X POST \
    -H "Content-Type: application/json" \
    -H "Accept:       application/json" \
    -d @push.json \
    http://localhost:8080/service/pushservice/api/v1/usage?pushId=id-20171212120000

$ cat push.json
{
    "accountId": "account-12345",
    "timestamp": 20171212201234
}

或者
$ curl -X POST \
    -H "Content-Type: application/json" \
    -d '{ "accountId": "account-12345", "timestamp": 20171212201234 }' \
    http://localhost:8080/service/pushservice/api/v1/usage?pushId=$(date "+%Y%m%d-%H%M%S")

運(yùn)行:

$ node server.js
Server started on 8080

3. 客戶端 - python

#!/usr/bin/python

import sys
import json
import ssl, urllib, urllib2

def invoke(url, method, datastr, cafile, certfile, keyfile):
    request = urllib2.Request(url)
    request.get_method = lambda: method

    if datastr != '':
       dataobj  = json.loads(datastr)      # string to object
       datajson = json.dumps(dataobj)      # object to json
       databyte = datajson.encode('utf-8') # json   to bytes

       request.add_data(databyte)
       request.add_header('Content-Type', 'application/json')

    contents = urllib2.urlopen(request).read()
    print contents
    sys.exit(0)


def main(argv):
    url      = 'http://localhost:8080/service/pushservice/api/v1/usage?id=id-20171212120000'
    method   = 'POST'
    datastr  = '{ "accountId": "account-12345", "timestamp": 20171212201234 }'  # must be json string
    #datastr  = ''
    cafile   = './tls-ca.pem'
    certfile = './tls-cert.pem'
    keyfile  = './tls-key.pem'

    invoke(url, method, datastr, cafile, certfile, keyfile)


if __name__ == "__main__":
   main(sys.argv[1:])

4. 客戶端 - node.js

'use strict';

var http = require('http');

var channels = {
    "accountId": "account-12345",
    "timestamp": 20171212201234
};

var bodyString = JSON.stringify(channels);

var headers = {
    'Accept': '*/*',
    'Content-Length': bodyString.length,
    'Content-Type': 'application/json'
};

var options = {
    hostname: 'localhost',
    port: 8080,
    path: '/service/pushservice/api/v1/usage?id=id-20171212120000',
    method: 'POST',
    auth: 'Hello' + ":" + 'World!',
    json: true,
    headers: headers
};


var req = http.request(options, (response) => {
    response.setEncoding('utf-8');
    var body = '';

    response.on('data', (d) => {
        body = body + d;
    });

    response.on('end', function() {
        console.log("statusCode: ", response.statusCode);
        console.log("response  : ", body);
        //console.log("json      : ", JSON.parse(body));
    });
});

req.on('error', (e) => {
    console.log("Report metering data failed, error: " + e);
});

req.write(bodyString);
req.end();

5.其他事項(xiàng)

如果用到的express包沒有安裝,則需要執(zhí)行下面命令安裝:

$ npm install express

缺省會(huì)安裝到 ~/.npm目錄下面。

6. 非application/json格式j(luò)son數(shù)據(jù)

處理自定義格式j(luò)son
有時(shí)當(dāng)客戶端client發(fā)送json數(shù)據(jù),但并沒有在HTTP headers里面指定Content-Type類型為json數(shù)據(jù),或者指定了一個(gè)自定義的json格式,例如:

curl -v -X POST -d @push.json http://localhost:8080/...
or
curl -v -X POST -H "Content-Type: application/com.your.company.usage+json" -d @push.json http://localhost:8080/...

此時(shí)就無法使用bodyParser.json()來解析body的內(nèi)容,辦法是強(qiáng)行把Content-Type改成json

app.use(function (req, res, next) {
    req.headers['content-type'] = 'application/json';
    next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容