guolz

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\'
 }

分类:

技术点:

相关文章:

  • 2021-06-20
  • 2021-09-12
  • 2021-09-22
  • 2022-01-09
  • 2022-12-23
猜你喜欢
  • 2021-04-04
  • 2021-10-15
  • 2022-12-23
  • 2021-08-29
  • 2022-12-23
  • 2021-12-26
  • 2021-04-04
相关资源
相似解决方案