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

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

加个好友,技术交流

1628738909466805.jpg