zoukankan      html  css  js  c++  java
  • node的http与前端交互示例(入门)

    一、目录(node_modules是npm install后新增的)

    node 和 npm 版本

     npm install http

    二、node下的index.js

    var http = require('http')
    
    http.createServer(function (request, response) {
    
        response.writeHead(200, { 'Content-Type': 'text/plain' })
        
        request.on('data', function (chunk) {
          response.write(chunk)
      })
    
      request.on('end', function () {
          response.end('hello node world')
      })
      
    }).listen(8090)

    监听localhost的8090端口

    三、前端home.html页面

    <!DOCTYPE html>
    <html>
    <head>
        <title>node home</title>
    </head>
    <body>
        <script type="text/javascript">
            window.onload = function () {
                var body = document.getElmentsByTagName('body')[0]
    
                var xhr = new XMLHttpRequest()
                xhr.open('GET', '/localhost:8090', false)
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.Status === 200) {
                        body.innerHtml = xhr.responseText
                    }
                }
            }
        </script>
    </body>
    </html>

    简单测试,直接使用了原生JavaScript的ajax,发送get请求到localhost:8090,返回结果输出到页面上

    四、测试效果

     

     Headers也能看到200返回码~  绿灯

  • 相关阅读:
    【BZOJ 1455】罗马游戏
    【UR #2】树上GCD
    1067: [SCOI2007]降雨量
    1068: [SCOI2007]压缩
    1066: [SCOI2007]蜥蜴
    1065: [NOI2008]奥运物流
    1064: [Noi2008]假面舞会
    1063: [Noi2008]道路设计
    2329: [HNOI2011]括号修复
    2734: [HNOI2012]集合选数
  • 原文地址:https://www.cnblogs.com/zhuxingqing/p/11526558.html
Copyright © 2011-2022 走看看