网络操作
最后更新于:2022-04-02 03:31:02
[TOC]
## http 模块
demo
```
//main.js
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, { 'Content-Type': 'text-plain' });
response.end('Hello World\n');
}).listen(8124);
```
`> node main.js `
通过`http://loalhost:8124`访问
> 在Linux系统下,监听1024以下端口需要root权限。因此,如果想监听80或443端口的话,需要使用sudo命令启动程序。
### 客户端访问
1. post
```
var http = require("http");
var options = {
hostname: 'www.example.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var request = http.request(options, function (response) {
console.log(response);
});
request.write('Hello World');
request.end();
```
2. get
`http.get('http://www.example.com/', function (response) {});`
```
var http = require("http");
http.get('http://localhost:8124/', function (response) {
var body = [];
console.log(response.statusCode); //200
console.log(response.headers); //打印头信息
response.on('data', function (chunk) {
body.push(chunk);
});
response.on('end', function () {
body = Buffer.concat(body);
console.log(body.toString()); //网址返回内容
});
});
```
## HTTPS 模块
1. 创建https 的服务器
```
var options = {
key: fs.readFileSync('./ssl/default.key'),
cert: fs.readFileSync('./ssl/default.cer')
};
var server = https.createServer(options, function (request, response) {
// ...
});
```
2. 客户端 访问https
```
var options = {
hostname: 'www.example.com',
port: 443,
path: '/',
method: 'GET',
rejectUnauthorized:false //可是非颁发机构 颁发的 证书安全问题 不进行提示
};
var request = https.request(options, function (response) {});
request.end();
```
## URL 模块
1.` url.parse` 把url 字符串转为对象
```
url.parse('http://user:pass@host.com:8080/p/a/t/h?query=string#hash');
/* =>
{ protocol: 'http:',
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' }
*/
```
`.parse` 第二个参数为true 则`query`字段转为对象
2. `url.format` 把url对象转为url字符串
```
url.format({
protocol: 'http:',
host: 'www.example.com',
pathname: '/p/a/t/h',
search: 'query=string'
});
//http://www.example.com/p/a/t/h?query=string
```
3. `url.resolve`
```js
url.resolve('http://www.example.com/foo/bar', '../baz');
//http://www.example.com/baz
```
## Query String 模块
```js
querystring.parse('foo=bar&baz=qux&baz=quux&corge');
//{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
//'foo=bar&baz=qux&baz=quux&corge='
```
## zlib
> [参考](http://nqdeng.github.io/7-days-nodejs/#4.2.5)
zlib模块提供了数据压缩和解压的功能。当我们处理HTTP请求和响应时,可能需要用到这个模块。
## Net
';