319 CORS 跨域资源共享


07.CORS跨域资源共享.html

<!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:3001/cross',
                success: function (data) {
                    console.log(data)
                }
            })
        };
    </script>
</body>
</html>

服务端代码

// 拦截所有请求
app.use((req, res, next) => {
    // 1.允许哪些客户端访问我
    // * 代表允许所有的客户端访问我
    res.header('Access-Control-Allow-Origin', '*')
    // 2.允许客户端使用哪些请求方法访问我
    res.header('Access-Control-Allow-Methods', 'get,post')
    next();
});

猜你喜欢

转载自www.cnblogs.com/jianjie/p/12354258.html