首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Promise实现原生JS的Ajax请求(后端使用Node.js)

Promise实现原生JS的Ajax请求(后端使用Node.js)

作者头像
从入门到进错门
发布2018-12-21 15:54:48
4K0
发布2018-12-21 15:54:48
举报

最近在学习ES6的相关知识,看完了Promise,于是打算用Promise实现一个原生JS的Ajax例子,顺便复习一下Node的相关知识。

说搞就搞,先写后端

项目目录结构

后端使用的是Express框架,具体步骤如下:

  • npm init

初始化,这个就一直下一步就行了,需要注意的是项目文件夹名不能为中文。

  • npm install express --save

使用 npm 安装 express

  • 此时的目录结构应该是这样的:node_modules/ package.json package-lock.json
  • 新建文件:server.js,和上面的文件同级。
  • 此时的目录结构是这样的:node_modules/ package.json package-lock.json server.js

写server

直接看代码:

code:

const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const app = new express();
// 创建 json 解析
app.use(bodyParser.json());
// 创建 application/x-www-form-urlencoded 编码解析
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static('public'));

const server = app.listen(3000, () => {
    const host = server.address().address;
    const port = server.address().port;
    console.log('app listening at http://%s:%s', host, port);
});

let data = [
    { name: 'zhangsan', age: 23 },
    { name: 'lisi', age: 24 },
    { name: 'wangwu', age: 26 },
    { name: 'zhaoliu', age: 27 },
    { name: 'tianqi', age: 29 }
];

app.get('/gettest', (req, res) => {
    console.log(req.body);
    res.status(200),
        res.json(data)
});
app.post('/posttest', function(req, res) {
    console.log(req.body);
    res.status(200),
        res.json(data)
});

在代码中写了两个处理请求的方法:

  • /gettest:处理get请求
  • /posttest:处理post请求

代码挺简单的,就不一一解释了。

启动服务

执行:node server.js,启动服务 使用浏览器访问:http://localhost:3000/

此时可以看见页面中返回了在server中定义的data里面的数据:

[
    { name: 'zhangsan', age: 23 },
    { name: 'lisi', age: 24 },
    { name: 'wangwu', age: 26 },
    { name: 'zhaoliu', age: 27 },
    { name: 'tianqi', age: 29 }
];

后台搞定了,接下来是本文的重头戏,撸前端。

再来看看前端

新建前端页面index.html

因为后端指定了静态文件在public,于是我们新建index.html文件,放在public文件夹下。public文件夹和server.js同级。

此时的目录结构是这样的:

│  package-lock.json
│  package.json
│  server.js
│
├─node_modules
└─public
        index.html

开始撸

index.html中开始撸Promise

code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        const myAjax = function(data, url) {
            console.log(data);
            console.log(url);
            const promise = new Promise((resolve, reject) => {
                const stateChange = function() {
                    if (this.readyState !== 4) {
                        return;
                    }
                    if (this.status === 200) {
                        resolve(this.response);
                    } else {
                        reject(new Error(this.statusText));
                    }
                };
                const myHttp = new XMLHttpRequest();
                myHttp.open('POST', url, 'true');
                myHttp.onreadystatechange = stateChange;
                myHttp.responseType = 'json';
                myHttp.setRequestHeader('Content-Type', 'application/json');
                myHttp.send(JSON.stringify(data));

            });
            return promise;
        };
        let data = {
            user: 'root'
        };
        let url = 'http://localhost:3000/posttest';
        myAjax(data, url).then(res => {
            console.log(res);
        }).catch(err => {
            console.log(err);
        });
    </script>
</body>

</html>

此处是使用Promise写的AjaxPOST请求,GET请求就不写了。Promise还是挺好用的。

运行结果

最终结果
最终结果
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 说搞就搞,先写后端
    • 项目目录结构
      • 写server
        • 启动服务
        • 再来看看前端
          • 新建前端页面index.html
            • 开始撸
            • 运行结果
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档