Write interface - solve interface cross-domain problem based on cors

First, you can find the online jquery.min.js file on the Staticfile CDN website, so you don’t need to download it and import it

 Code in 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;

Code in 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. The code in 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>

Finally, open the 1.html page and click the GET and POST buttons, the effect is as follows:         

 

Guess you like

Origin blog.csdn.net/qq_43781887/article/details/127258992