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返回码~  绿灯

  • 相关阅读:
    TCP 基础知识
    Spring Boot 实战 —— 日志框架 Log4j2 SLF4J 的学习
    MySQL 实战笔记
    Java 基础
    RPM 包的构建
    RPM 包的构建
    9. 桶排序
    8. 基数排序
    7. 计数排序
    6. 快速排序
  • 原文地址:https://www.cnblogs.com/zhuxingqing/p/11526558.html
Copyright © 2011-2022 走看看