API使用和创建

264 阅读1分钟
一、API是啥?

API即用来与其他应用交互传递信息的端口,方便团队开发,前后端分离等

参考文章:blog.csdn.net/Noah_ZX/art…

二、如何创建和使用

创建

一般使用于服务端,下面使用Node.js创建一个API接口
此时我们就可以根据下面代码编写API文档了

请求参数

名称说明
name必要

响应参数

名称说明
code1 正常 , -1 异常
msg提示
data正常返回的数据
import express from 'express';
const app = express()


// 解析请求体
app.use(express.json())
app.use(express.urlencoded({ extended: false }))


// 数据
let infor = {
    zhangsan : {
        name:'zhangsan',
        age:16,
        home:'shangai'
    },
    lishi : {
        name:'lishi',
        age:17,
        home:'guangzhou'
    }

}

// 监听post方式下api路径
app.post('/api',(req,res) => {
    if(req.body.name){
        let name = req.body.name
        let data = infor[name]
        res.send({
            code:1,
            msg:"Success!",
            data:data

        })
    }
    else {
        res.send({
            code:-1,
            msg:'缺少name参数'
        })
    }
});


// 创建监听服务
let port = 9090  // 端口号
app.listen(port)

使用

下面使用HTML调用

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="infodiv"></div>
    <input ref="reference" id="name" value="zhangsan">
    <button type="button" onclick="info(document.getElementById('name').value)">
        获取信息
    </button>
</body>

<script>
    // var info = document.createTextNode()
    let infodiv = document.getElementById('infodiv')
    function info(value) {
        console.log(value);
        let data = {
            name: value
        }
        axios.post('http://localhost:9090/api', data)
            .then(res => {
                document.getElementById('infodiv').innerHTML = "<div></div>"
                for (let text in res.data.data) {
                    console.log(res.data.data[text]);
                    let h = document.createElement("h1")
                    h.appendChild(document.createTextNode(text + ":" + res.data.data[text] + "\n\t"))
                    infodiv.appendChild(h)
                }
            })
            .catch(error => {
                console.log(error)
            })
    } 
</script>

</html>