node.js使用express发布REST API servi
2017-11-14 本文已影响20人
CodingCode
使用express发布REST API service的例子。
并通过curl/python/node.js客户端分别发送请求。
1. node.js server 端
接收client发出的POST请求
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")
运行:
$ 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.其他事项
如果用到的express包没有安装,则需要执行下面命令安装:
$ npm install express
缺省会安装到 ~/.npm目录下面。
6. 非application/json格式json数据
处理自定义格式json
有时当客户端client发送json数据,但并没有在HTTP headers里面指定Content-Type类型为json数据,或者指定了一个自定义的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/...
此时就无法使用bodyParser.json()来解析body的内容,办法是强行把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 }));