编写接口-基于cors解决接口跨域问题

首先在Staticfile CDN这个网站可以找到在线的jquery.min.js文件,就不用下载之后导入了

 router.js中的代码:

// 1.导入express包
const express = require('express');
// 2.创建路由
const router = express.Router();
// 3.挂载具体路由
router.get('/get', (req, res) => {
    res.send({
        status: 100,
        msg: 'getmsg',
        data: req.body
    })
})
router.post('/post', (req, res) => {
        res.send({
            status: 101,
            msg: 'postmsg',
            data: req.body
        })
    })
    // 4.向外导出路由对象
module.exports = router;

sy.js中的代码:

// 1.导入express包
const express = require('express');
const { process_params } = require('express/lib/router');
// 创建一个web服务器
const app = express();
app.use(express.urlencoded({ extends: false }));
// 导入cors模块
const cors = require('cors');
app.use(cors());
// 导入路由
const router = require('./router');
// 注册路由
app.use(router);
app.listen(81, () => {
    console.log('running!');
})

1.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">
    <title>Document</title>
    <script src="https://cdn.staticfile.org/jquery/3.6.1/jquery.min.js"></script>
</head>

<body>
    <button id="btnget">GET</button>
    <button id="btnpost">POST</button>
    <script>
        $(function() {
            // 1.测试GET接口
            $('#btnget').on('click', function() {
                    // 发起ajax请求
                    $.ajax({
                        type: 'GET',
                        url: 'http://127.0.0.1:81/get',
                        data: {
                            name: 'sy',
                            age: 18
                        },
                        success: function(res) {
                            console.log(res);
                        }

                    })
                })
                // 2.测试POST接口
            $('#btnpost').on('click', function() {
                // 发起ajax请求
                $.ajax({
                    type: 'POST',
                    url: 'http://127.0.0.1:81/post',
                    data: {
                        name: 'oliver',
                        age: 22
                    },
                    success: function(res) {
                        console.log(res);
                    }

                })
            })
        })
    </script>
</body>

</html>

最后打开1.html页面点击GET和POST按钮效果如下:         

猜你喜欢

转载自blog.csdn.net/qq_43781887/article/details/127258992