我是靠谱客的博主 热心自行车,这篇文章主要介绍node的http与前端交互示例(入门),现在分享给大家,希望可以做个参考。

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

node 和 npm 版本

 

 npm install http

 

二、node下的index.js

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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页面

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!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

最后

以上就是热心自行车最近收集整理的关于node的http与前端交互示例(入门)的全部内容,更多相关node内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部