创建新的服务器
创建一个简单的服务
var http = require("http"); var server = http.createServer(); server.listen(8888);
这段代码只会启动一个侦听8888端口的服务器,不会应答,不会任何事,所以是无意义的。
下面创建一个有意义的服务器
var http = require("http"); http.createServer(function(request, response) { console.log('get request'); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);
结果:
//服务端 $ node http.js get request
//客户端 $ curl localhost:8888 Hello World
这里我们通过response.writeHead发送一个请求状态码和内容类型,使用 response.write() 函数在HTTP响应主体中发送文本“Hello World"。
response.end()这个方法告诉服务器,所有的响应头和响应体已经发送,服务器可以认为消息结束。
在curl下测试不出我们请求两次的问题,我们在浏览器端输入:http://localhost:8888/
Request Pathname Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: '/', path: '/', href: '/' } Request Pathname Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: '/favicon.ico', path: '/favicon.ico', href: '/favicon.ico' }
发现请求了两次。
注意:当我们在服务器访问网页时,我们的服务器可能会输出两次“get request”。那是因为大部分浏览器都会在你访问 http://localhost:8888/时尝试读取 http://localhost:8888/favicon.ico )
解析请求路径
这时候我们需要另外一个模块,url
var http = require("http"); var url = require("url") http.createServer(function(request, response) { var pathname = url.parse(request.url).pathname; console.log('Request Pathname ',pathname); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);
发送请求:localhost:8888/demo/test
curl localhost:8888/demo/test
查看解析的url结果:
Request Pathname /demo/test
我们取到浏览请求的url,这个可以帮助我们做路由映射。
url.parse很神奇,那我们再来多了解一点。
将原来的代码处url.parse修改一下
pathname = url.parse(request.url)
发送请求:http://localhost:8888/select?page=10&blog=nodejs
Url {
protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?page=10&blog=nodejs', query: 'page=10&blog=nodejs', pathname: '/select', path: '/select?page=10&blog=nodejs', href: '/select?page=10&blog=nodejs' }
这就是整个解析后的url。
解析请求参数
使用querystringnodejs自带的模块解析参数
修改一下代码:
var http = require("http"); var url = require("url"); var querystring = require('querystring') http.createServer(function(request, response) { var pathname = url.parse(request.url); var query = querystring.parse(pathname.query); console.log('query ',query); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);
query { page: '10', blog: 'nodejs' }
querystring.parse()有点类似于JSON.parse()
querystring.stringify()有点类似于JSON.stringify()
查看有querystring 哪些方法:
> var querystring = require('querystring') undefined > querystring { unescapeBuffer: [Function], unescape: [Function], escape: [Function], encode: [Function], stringify: [Function], decode: [Function], parse: [Function] }
发送post请求
这个例子有点复杂。
我们先创建一个服务器localhost:8000,然后通过自定义路由来处理请求。这里我们还是用http.request()发送了一个到localhost:8000/test的请求,并尝试获取post的数据。
var http = require("http"); var url = require("url"); var querystring = require('querystring') http.createServer(function(request, response) { var pathname = url.parse(request.url); var query = querystring.parse(pathname.query); if (pathname.pathname === '/getDo') { //处理localhost:8000/getDo response.writeHead(200, { "Content-Type": "text/plain" }); response.write("Hello World"); response.end(); } else if (pathname.pathname === '/postDo') { //处理localhost:8000/postDo postTest(response); } else if (pathname.pathname === '/test') { var jsonData = ''; request.on("data", function(data) { jsonData += data console.log('接受数据中。。。'); }); request.on("end", function() { console.log('接受完成!'); console.log(querystring.parse(jsonData)); }) } }).listen(8888); function postTest(response) { var postData = querystring.stringify({ 'msg': 'Hello World!' }) //发送post请求localhost:8000/test并带上参数postData var options = { hostname: 'localhost', port: 8888, path: '/test', method: 'POST', headers: { 'Content-Type': '"text/plain', 'Content-Length': postData.length } }; var req = http.request(options); req.write(postData); req.end() }
接受数据中。。。
接受完成!
{ msg: 'Hello World!' }
这里我们通过请求localhost:8000/postDo的时候,又通过http发送了localhost:8000/test这个请求,并通过req.write(postData)带上了post的参数。
应该这里没有使用任何框架,post的数据必须通过
var jsonData = ''; request.on("data", function(data) { jsonData += data console.log('接受数据中。。。'); }); request.on("end", function() { console.log('接受完成!'); console.log(querystring.parse(jsonData)); })
这样的形式来拼接。