关于node.js:node的http与前端交互示例入门

9次阅读

共计 808 个字符,预计需要花费 3 分钟才能阅读完成。

一、目录 (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 返回码~  绿灯

正文完
 0