zoukankan      html  css  js  c++  java
  • node创建一个简单的web服务

    本文将如何用node创建一个简单的web服务,过程也很简单呢~

    开始之前要先安装node.js

    1.创建一个最简单的服务

    // server.js
    const http = require('http')
    
    http.createServer(function (request, response) {
      console.log('request come', request.url)
      
      response.end('132')
      
    }).listen(8888)
    

    函数接受request和response参数:

    request:请求我们这个服务发送的内容都会被封装在这个request对象里

    response:服务返回内容就是对这个request对象进行操作。

    response.end() 就是服务返回的内容,如果服务不返回内容,页面就会报错(一直处于加载中的状态)

    listen() 就是当前监听的端口号啦

    创建完js文件后,就要启动服务了,打开命令行,输入

    node server.js // node 刚才创建的js名称

    在服务器中输入 localhost:8888 就可以访问我们这个服务了。

    2.在server中读取html

    // server2.js
    const http = require('http')
    const fs = require('fs')
    
    http.createServer((request, response)=> {
        console.log('request come', request.url)
    
        const html = fs.readFileSync('index.html', 'utf-8')
        response.writeHead(200, {
            'Content-Type': 'text/html'
        })
    
        response.end(html)
        
    }).listen(8887)
    
    console.log('listen at localhost:8887')
    <!--index.html-->
    <body>
        <p>server</p>
    </body>

    这时候在浏览器里输入localhost:8888 就可以这个html了

    简单的创建服务已经完成啦。学到这里肯定觉得太简单了。那么请看下面的部分。

    1.前端跨域及其解决方案

    2.前端需要了解的HTTP协议

  • 相关阅读:
    安卓权威编程指南-笔记(第24章 Looper Handler 和 HandlerThread)
    AndroidImageSlider
    ToolBar的使用
    安卓权威编程指南-笔记(第26章 服务的作用)
    关于两个update语句互相死锁的显现,加深我们对锁的了解 转载
    js 原型和构造方法 转载
    关于distinct 和group by的去重逻辑浅析
    tab 下一个
    当前浏览器版本
    清除li间隔
  • 原文地址:https://www.cnblogs.com/daisy-ramble/p/10329930.html
Copyright © 2011-2022 走看看