node跨域学习

node 跨域 cookie 预检请求,跨域的处理


#我们看下app.js

const fs = require("fs");
const http = require('http');
http.createServer((req, res) => {
    if (req.url == "/api/users") {
        if (req.headers.origin === "http://localhost:3000") {
            res.setHeader("Access-Control-Allow-Origin", req.headers.origin); //需要显示设置来源,不能使用‘*’

            res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
            res.setHeader("Access-Control-Allow-Credentials", true); //需要加上这个

            res.setHeader("Content-Type", "application/json");

            console.log(req.headers.cookie);
            res.end(JSON.stringify([{ id: "1002", name: "kk" }, {
                id: "2332",
                name: "actions"
            }]));
        }



    }

}).listen(4000);

index.html

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <p>3000端口的页面</p>
    <p>data</p>
    <script>

        (async () => {
            // 调用函数的函数体
            axios.defaults.withCredentials = true;

            let response = await axios.get("http://localhost:4000/api/users");
            console.log(response.data);
            document.writeln(`response + ${JSON.stringify(response.data)}`);
        })();
    </script>
</body>

</html>

action.js

const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
    if (req.url === "/index.html") {
        fs.readFile("./index.html", (err, data) => {
            if (!err) {
                //向后台发送 html  页面
                res.setHeader("Content-Type", "text/html;charset=utf-8");
                res.setHeader("Set-Cookie", "cc=99");
                res.end(data);
            } else {
                res.statusCode = 401;
                res.end("error code");
            }

        });
    } else if (req.url === "/json") {
        // 向后台发送json 数据
        res.setHeader("Content-Tyoe", "application/json");
        res.end(JSON.stringify([{ id: 1001, name: "action" }, { id: 1002, name: "kk" }]));
    }
});

server.listen(3000);

在这里插入图片描述我们可以看到在 localhost:3000 去跨域访问了4000 的数据

猜你喜欢

转载自blog.csdn.net/qq_15009739/article/details/108097117