NodeJS 入门 (一)

NodeJS没有web容器的概念

NodeJS需要对每一个请求进行路由处理,包括脚本,样式,图片等等任何请求

const http = require('http');
const server = http.createServer(function(req, res) {
	res.writeHead(200, {'content-type': 'text/html;charset=utf-8'});
	res.end('<h1>hello nodejs</h1>');
})
server.listen(8080, function() {
	console.log('ready!!!');
})

NodeJS根据请求URL来判断返回的资源

const http = require('http');
const fs = require('fs');
const server = http.createServer(function(req, res) {
	if(req.url === '/test') {
		fs.readFile('./test.html', function(err, data) {
			res.writeHead(200, {'content-type': 'text/html;charset=urf-8'});
			res.end(data);
		});
	} else if(req.url === '/home') {
		fs.readFile('./home.html', function(err, data) {
			res.writeHead(200, {'content-type': 'text/html;charset=utf-8'});
			res.end(data);
		})
	} else {
		res.writeHead(404, {'content-type': 'text/html;charset=utf-8'});
		res.end('404 NOT FOUND');
	}
})
server.listen(8080, function() {
	console.log('ready!!!');
})

HTTP模块

必须使用res.end()否则服务器会一直处于挂起状态

res.end()之前可以使用res.write()来想浏览器端传输信息

const http = require('http');
const server = http.createServer(function(req, res){
    res.writeHead(200, {'content-type': 'text/html;charset=urf-8'});
    res.write('<h1>first title</h1>');
    res.write('<h1>second title</h1>');
    res.end();
})

url模块

本模块专门用来处理url地址,基本用法如下

const url = require('url');
url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash");
{
  protocol: 'http:',
  slashes: true,
  auth: 'user:pass',
  host: 'host.com:8080',
  port: '8080',
  hostname: 'host.com',
  hash: '#hash',
  search: '?query=string',
  query: 'query=string',
  pathname: '/p/a/t/h',
  path: '/p/a/t/h?query=string',
  href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
 }
posted @ 2017-09-18 12:28  LZnism  阅读(160)  评论(0)    收藏  举报