codecamp

Node.js Web

HTTP响应代码

HTTP规范包含大量可以回到客户端的服务器响应代码。我们将在大多数应用程序中使用一些更常见的响应。

代码含义描述
200OK一切进行顺利。
301Moved Permanently请求的URL已移动,客户端应该在响应中指定的URL重新请求它。
400Bad Request客户端请求的格式无效,需要修复。
401Unauthorized客户端无权查看其要求的内容。
403Forbidden服务器拒绝处理此请求。 这与401不同,客户端可以使用身份验证再次尝试。
404Not Found客户端要求的东西不存在。
500Internal Server Error发生了某种情况,导致服务器无法处理请求。
503Service Unavailable表示某种运行时故障。

第一个JSON服务器

这里是trivial服务器,它保存在simple_server.js:

var http = require("http");
//www.w3cschool.cn
function  handle_incoming_request (req, res) {
    console.log("INCOMING REQUEST: " + req.method + " " + req.url);
    res.writeHead(200, { "Content-Type" : "application/json" });
    res.end(JSON.stringify( { error: null }) + "\n");
}

var s = http.createServer(handle_incoming_request);
s.listen(8080);

通过键入在一个终端窗口(Mac/Linux)或命令提示符(Windows)中运行此程序

node simple_server.js

现在,在另一个终端窗口中,键入

curl -X GET http://localhost:8080

我们应该看到

INCOMING REQUEST: GET /

在你运行curl命令的窗口中,你应该看到

{"error":null}


Node.js 异步编程
Node.js 缓冲区(Buffer)
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }