标题 | NodeJS基础学习(服务器的创建) |
范文 | NodeJS自带服务器,这点相对于apache、nginx、iis等服务器相比,在功能上可能有制约,但是由于即装即用免配置的特点,用来做接口测试和数据模拟还是相当方便的。这也是我大爱NodeJS的一个原因。 创建简单的服务器 官网的实例代码如下所示: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello Node.js\n'); res.end('Hello World'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); 启动服务器,执行该脚本后在浏览器输入栏填写地址:http://127.0.0.1:1337/,即可看到浏览器显示Hello World文本。 除了创建方式,脚本的执行步骤不介绍外,有几点我们是可以关注的,分别如下: 输出头信息(res.writeHead) API地址:https://nodejs.org/api/http.html#http_response_writehead_statuscode_st... 作用:定制响应的头信息。 在上面的示例中,其作用是请求ok(http status为200),输出的信息是普通的文本信息('Content-Type': 'text/plain')。 响应主体的信息(res.write) API地址:https://nodejs.org/api/http.html#http_response_write_chunk_encoding_ca... 作用概述:写入响应主体的信息,这些信息被浏览器接受后,会显示在浏览器中。 发出响应信息(res.end) API地址:https://nodejs.org/api/http.html#http_response_end_data_encoding_callb... 作用概述:该方法一经调用,将会向客户端发出响应信息 拓展 Node.js向可客户端输出json var http = require('http'); var data = {key: 'value', hello: 'world'}; var srv = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(data)); }); srv.listen(8080, function() { console.log('listening on localhost:8080'); }); Node.js向可客户端输出XML var http = require('http'); var data = '<?xml version="1.0" encoding="UTF-8"?><root><tag>text</tag></root>'; var srv = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'application/xml'}); res.end(data); }); srv.listen(8080, function() { console.log('listening on localhost:8080'); }); |
随便看 |
|
在线学习网范文大全提供好词好句、学习总结、工作总结、演讲稿等写作素材及范文模板,是学习及工作的有利工具。