跨域--服务器端向服务器端发送请求-第三方模块got

93 阅读1分钟

客户端代码不变

客户端向同源服务器端①发送请求

服务器端①再向跨域服务器端②发送请求

跨域是对浏览器端的限制,对服务器端发送请求没有限制

02.png

客户端代码

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

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <button id="btn">点我发送请求</button>
    <script src="/js/ajax.js"></script>
    <script>
        // 获取按钮
        var btn = document.getElementById('btn');
        // 为按钮添加点击事件
        btn.onclick = function() {
            ajax({
                type: 'get',
                url: 'http://localhost:3000/server',
                success: function(data) {
                    console.log(data);
                }
            })
        };
    </script>
</body>

</html>

服务器端代码

const got = require('got');
app.get('/server', async(req, res) => {
    try {
        const response = await got('http://localhost:3001/cross');
        // console.log(response.body);
        res.send(response.body)
    } catch (error) {
        console.log(error);
    }
    // res.send('123');
});