ホームページ  >  記事  >  ウェブフロントエンド  >  Node.js は HttpStatusCode 補助クラスを生成し、それを npm_Basic 知識に公開します

Node.js は HttpStatusCode 補助クラスを生成し、それを npm_Basic 知識に公開します

WBOY
WBOYオリジナル
2016-05-16 17:37:521496ブラウズ

優れた Restfull API は、サービス URL のセマンティクス、可読性、冪等性、直交性に依存するだけでなく、http ステータス コードも依存します。適切な Http ステータス コードは、ユーザーに 200 などの適切な応答を返します。は通常の成功を意味し、201 は作成の成功を意味し、409 競合、404 リソースが存在しないなどを意味します。そこで、node.js mongodb angularjs に基づいてデモを作成していたときに、node.js Express が対応する補助クラスを提供していないことがわかりました。しかし、言語レベルのセマンティクスのない 201,404 のようなものをあちこちに溢れさせるのは好きではなかったので、ついに自分で書くことにしましたが、同時に非常に怠け者でもあり、繰り返しの大変な作業は好きではありません。どうすればよいでしょうか。次に、私が最も使い慣れている C# の HttpStatusCode 列挙体からそれをコピーします。最後に、Mac での簡素化のために、node.js を使用して httpstatuscode に関する msdn のドキュメントを解析し、node.js 補助クラスを生成しました。

コードは非常に簡単です:

コードをコピー コードは次のとおりです。

var http = require('http') ;

var fs = require('fs');

var $ = require('jquery');

var Output = "httpStatusCode/index.js";

(function(){



String.format = function() {

var s = argument[0];

for ( var i = 0; i < argument.length - 1; i ) {

var reg = new RegExp("\{" i "\}", "gm");

s = s.replace(reg, argument[i 1]);

}

return s;

};




var options = {

ホスト:'msdn.microsoft.com',

ポート:80,

パス:'/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("エラーが発生しました: " 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());

});

ステータスを返す;

} ;



function generatedCode(status){

var code = "";

code = "exports.httpStatusCode = " JSON。 stringify(status ) ";";

戻りコード;

};



function writeFile(code){

fs .writeFile( 出力, コード, function(err) {

if(err) {

console.log(err);

} else {

console.log("ファイルは保存されました " 出力 "!");

}

});




function handler(html){

var status = getHttpStatusCode(html);

var code =generateCode(status);

writeFile(code) ;

};




});

})();


コードは github でホストされています: https://github.com/greengerong/node-httpstatuscode

最終的に生成されるクラスは次のとおりです:

コードを表示
exports.httpStatusCode = {
"続行": 100、
"スイッチングプロトコル": 101、
"OK": 200、
"作成": 201、
"承認": 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、
"未使用": 306、
"TemporaryRedirect": 307、
"RedirectKeepVerb": 307、
"BadRequest": 400、
"Unauthorized": 401、
"PaymentRequired": 402、
"Forbidden": 403、
"NotFound": 404、
"MethodNotAllowed" : 405、
"NotAcceptable": 406、
"ProxyAuthenticationRequired": 407、
"RequestTimeout": 408、
"競合": 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 だけを必要とします。

コードをコピー

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。