Cocos学习-使用 XMLHttpRequest 发送请求

利用node.js搭建一个简易服务器,尝试使用 XMLHttpRequest 发送  请求

XMLHttpRequest 是一种使用 JavaScript 发送 HTTP 请求的原始方式,它允许您从浏览器中异步获取数据,而无需刷新页面。这使得您可以更快地响应用户的操作,并且可以动态更新内容,而无需重新加载整个页面。

搭建服务器:

在文件夹下面创建一个.js文件,我创建为index.js,用VsCode等编程工具打开后做基础的搭建:

//引入http
const http = require('http');
//http.createServer()创建一个web服务器
//req是请求功能的相关对象,res是响应功能的相关对象,有请求过来
//http.createServer()会返回一个server实例
const server = http.createServer((req,res) => {
    const { pathname,query }= url.parse(req.url)
    if(req.method === 'GET'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('响应了GET请求')
    }else if(req.method === 'POST'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('响应了POST请求')
    }
    
});
//通过server.listen()设置当前服务器应该监听哪个端口
server.listen(3000,()=>{
    console.log('Server is coming');
})

在终端中进入index.js文件的目录下,运行index.js

网页结果:

在实际的网页效果中,除了http://localhost:3000/这个基地址,还有一些接口地址,比如http://localhost:3000/userInfo,/userInfo就是接口地址,所以判别的时候,就是判别后面的接口地址

node.js中专门提供了一个模块,用来进行url处理,

const url = require('url')

url具有一个parse的方法,可以对req.url做转换,req.url就是请求的地址

如果不希望接收所有的话,可以通过解构的方式来解构出其中的接口地址,

const {pathname}= url.parse(req.url)

设置当请求方式是‘GET’并且接口地址是‘/getinfo’的时候才能显示响应请求,不然就显示

Not Found,测试代码:

const http = require('http');
const url = require('url')
const server = http.createServer((req,res) => {
    const {pathname}= url.parse(req.url)
    if(req.method === 'GET'&&pathname === '/getinfo'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('响应了GET请求,getinfo')
    }else if(req.method === 'POST'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('响应了POST请求')
    }else{
        res.statusCode = 404
        res.end('Not found')
    }
});

server.listen(3000,()=>{
    console.log('Server is coming');
})

http://localhost:3000/结果:

http://localhost:3000/getinfo结果:

为了尝试发送JSON对象,修改后端index.js,使得发送POST请求时,带有JSON对象

const http = require('http');
const url = require('url')
const server = http.createServer((req,res) => {
    const { pathname}= url.parse(req.url)
    res.setHeader('Access-Control-Allow-Origin',"*")
    if(req.method === 'GET'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('响应了GET请求')
    }else if(req.method === 'POST'){
        res.setHeader('Content-Type','application/json')
        res.end('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}')
    }else{
        res.statusCode = 404
        res.end('Not found')
    }
});

server.listen(3000,()=>{
    console.log('Server is coming');
})

我把脚本挂载到node上,开启鼠标监听,点击一次node就会使用 XMLHttpRequest 发送一次GET请求

    start () {
        this.node.on(cc.Node.EventType.MOUSE_UP, this.onMouseUp,this)
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
    }
    onMouseUp(){
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost:3000/');
        xhr.onload = () => {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        } else {
            console.error(`Error: ${xhr.status}`);
        }
        };
        xhr.send();
    }

结果(灰色方块是node)点击八次响应了八次:

要发送一个POST请求并带有 JSON 请求体,使用键盘监听,键盘按一次就发送一次:

    onKeyDown(){
        if(cc.macro.KEY.a){
            var xhr = new XMLHttpRequest();
            var url = 'http://localhost:3000/';
            xhr.open('POST', url);
            xhr.onload = () => {
                if (xhr.status === 200) {
                    var json = JSON.parse(xhr.responseText);
                    console.log(json);
                }else {
                    console.error(`Error: ${xhr.status}`);
                }
            };
            var data = JSON.stringify({ key: "value" });
            xhr.send(data);
        }
    }

结果:

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值