Nodejs创建简单的http服务

  1. 引入http模块

    let http = require('http');
    
  2. 创建服务实例

    let server = http.createServer();
    
  3. 等待请求

    server.on('request',(request,response) => {
          
          
        console.log('请求收到');
        let str = '';
        if (request.url == '/') {
          
          
            str = 'welcome to Home';
        } else {
          
          
            str = `welcome to ${
            
            request.url}`;
        }
        response.write(str);// 发送数据
        response.end();// 结束连接
             // 等价于
     	response.end(str);// 发送响应并结束响应(更常用)
    })
    
    1. 当客户端请求时,会自动触发服务器的request请求事件,然后调用回调函数

    2. 请求处理函数(回调函数)有两个参数

      1. request
        1. 请求对象可以用来获取客户端的一些请求信息
      2. response
        1. 响应对象可以用来给客户端发送响应信息
        2. 有一个方法:write可以用来给客户端发送响应数据
        3. write可以使用多次,但是最后一定要使用end,否则客户端会一直等待
    3. 绑定端口号,启动服务器

    server.listen(3000,() => {
          
          
        console.log('服务绑定成功');
    })
    
  4. 运行:在cmd或者webStorm或者拥有terminal的软件中输入node 当前js文件,即可运行服务。接着在浏览器窗口输入地址,本示例设置的是3000端口,则访问http://localhost:3000/即可访问nodejs创建的简单的http服务。

  5. 结束服务:关闭当前窗口或者ctrl+c

猜你喜欢

转载自blog.csdn.net/chen__cheng/article/details/114331316