node的http与前端交互示例(入门)

时间:2019-09-16
本文章向大家介绍node的http与前端交互示例(入门),主要包括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返回码~  绿灯

原文地址:https://www.cnblogs.com/zhuxingqing/p/11526558.html