node服务器

2018-11-06  本文已影响0人  广州芦苇科技web前端

作者: 叶茂;
标签: nodejs,http


http.createServer

function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server;
requsetListener: 接收到请求后的回调函数
    request: 包含请求信息的对象
    response: 包含返回信息的对象

return Server: 服务器对象
request.url
const http = require('http')
const url = require('url')

const server = http.createServer((request, response) => {
    
    // 获取请求参数
    // 第二个参数表示,是否将请求参数解析成对象形式
    const query = url.parse(request.url, true).query

    if (query.firstname) {

        // 设置响应头
        // 第一个参数表示状态吗,第二个参数用对象字面量表示消息头中各字段的值。
        response.writeHead(200, {'content-type': 'text/html;charset=utf8'})

        // 写入响应体
        response.write('Hello from node http: ')
        response.write(query.firstname.toUpperCase() + ' ')
        response.write(query.lastname.toUpperCase())
        // 完成本次响应
        response.end()

    } else {
        response.writeHead(400, {'content-type': 'text/html;charset=utf8'})
        response.end('bad quest')
    }
})

server.listen(8080, () => {
    console.log('listenning port 8080')
})

http.request

function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
第一个参数: 请求相关的信息,包括请求方式,请求地址等
第二个参数:请求成功后的回调
    回调函数的第一个参数接收response对象

const http = require('http')
const fs = require('fs')

const request = http.request({
    host: 'www.talkmoney.cn'
}, (response) => {
    if (response.statusCode >= 200 && response.statusCode < 300) {
       
        let html = ''
        // data事件表示接收到消息体
        response.on('data', (chunk) => {
            html += chunk
        })

        response.on('end', () => {
            fs.writeFile('./luwei.html', html, (err) => {
                if (err) return console.log('write file failed')
                console.log('write file success')
            })
        })
    } else {
        console.log('bad response')
    }
})

request.end()
http.get()
const http = require('http')

http.get('www.talkmoney.cn', (response) => {
    if (response.statusCode >= 200 && response.statusCode < 300) {
       console.log('good response')
    } else {
        console.log('bad response')
    }
})

多线程服务器

Cluster

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

const url = require('url')

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {

  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello' + 'worker ' + process.pid );
  }).listen(8000);
  
}
上一篇 下一篇

猜你喜欢

热点阅读