您好,登錄后才能下訂單哦!
本篇內容介紹了“如何利用Node.js為Node.js生成HttpStatusCode輔助類并發布到npm”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
作為一個好的Restfull Api不僅在于service url的語義,可讀性,冪等,正交,作為http狀態碼也很重要,一個好的Http Status Code給使用者一個很好的響應,比如200表示正常成功,201表示創建成功,409沖突,404資源不存在等等。所以在做一個基于node.js+mongodb+angularjs的demo時發現node.js express沒有提供相應的輔助類,但是本人不喜歡將201,404這類毫無語言層次語義的東西到處充斥著,所以最后決定自己寫一個,但是同時本人也很懶,不喜歡做重復的苦力活,怎么辦?那就從我最熟悉的c#中HttpStatusCode枚舉中copy出來吧,最后為了簡便在mac上所以采用了利用node.js去解析msdn關于httpstatuscode的文檔生成node.js的輔助類。
代碼很簡單:
var http = require('http');
var fs = require('fs');
var $ = require('jquery');
var output = "httpStatusCode/index.js";
(function(){
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
};
var options = {
host:'msdn.microsoft.com',
port:80,
path:'/zh-cn/library/system.net.httpstatuscode.aspx'
};
http.get(options,function (response) {
var html = "";
response.on("data",function (chunk) {
html += chunk;
}).on("end", function () {
handler(html);
}).on('error', function (e) {
console.log("Got error: " + e.message);
});
function getHttpStatusCode(htmlString) {
var $doc = $(html);
var rows = $doc.find("table#memberList tr:gt(0)");
var status = {};
rows.each(function(i,row){
status[$(row).find("td:eq(1)").text()] =
parseInt($(row).find("td:eq(2)").text().match(/\d+/).toString());
});
return status;
};
function generateCode(status){
var code = "";
code += "exports.httpStatusCode = " + JSON.stringify(status) + ";";
return code;
};
function writeFile(code){
fs.writeFile(output, code, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved " + output + "!");
}
});
};
function handler(html){
var status = getHttpStatusCode(html);
var code = generateCode(status);
writeFile(code);
};
});
})();
代碼寄宿在github:https://github.com/greengerong/node-httpstatuscode
最終生成類為:
exports.httpStatusCode = {
"Continue": 100,
"SwitchingProtocols": 101,
"OK": 200,
"Created": 201,
"Accepted": 202,
"NonAuthoritativeInformation": 203,
"NoContent": 204,
"ResetContent": 205,
"PartialContent": 206,
"MultipleChoices": 300,
"Ambiguous": 300,
"MovedPermanently": 301,
"Moved": 301,
"Found": 302,
"Redirect": 302,
"SeeOther": 303,
"RedirectMethod": 303,
"NotModified": 304,
"UseProxy": 305,
"Unused": 306,
"TemporaryRedirect": 307,
"RedirectKeepVerb": 307,
"BadRequest": 400,
"Unauthorized": 401,
"PaymentRequired": 402,
"Forbidden": 403,
"NotFound": 404,
"MethodNotAllowed": 405,
"NotAcceptable": 406,
"ProxyAuthenticationRequired": 407,
"RequestTimeout": 408,
"Conflict": 409,
"Gone": 410,
"LengthRequired": 411,
"PreconditionFailed": 412,
"RequestEntityTooLarge": 413,
"RequestUriTooLong": 414,
"UnsupportedMediaType": 415,
"RequestedRangeNotSatisfiable": 416,
"ExpectationFailed": 417,
"UpgradeRequired": 426,
"InternalServerError": 500,
"NotImplemented": 501,
"BadGateway": 502,
"ServiceUnavailable": 503,
"GatewayTimeout": 504,
"HttpVersionNotSupported": 505
};
最后考慮到或許還有很多像我一樣懶散的人,所以共享此代碼發布到了npm,只需要npm install httpstatuscode,便可以簡單實用,如下是一個測試demo:
var httpStatusCode = require("httpstatuscode").httpStatusCode;
var toBeEqual = function (actual,expected){
if(actual !== expected){
throw (actual + " not equal " + expected);
}
};
toBeEqual(httpStatusCode.OK,200);
toBeEqual(httpStatusCode.Created,201);
toBeEqual(httpStatusCode.BadRequest,400);
toBeEqual(httpStatusCode.InternalServerError,500);
console.log(httpStatusCode);
console.log("success");
“如何利用Node.js為Node.js生成HttpStatusCode輔助類并發布到npm”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。