node 代理服务器写法

以 express 为列子

proxy.js

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();
app.use(express.static(__dirname + '/'));
app.use('/api', createProxyMiddleware({ target: 'http://localhost:4000', changeOrigin: true }));
module.exports = app;

i ndex.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("/api/users");
            console.log(response.data);
            document.writeln(`response + ${JSON.stringify(response.data)}`);
        })();
    </script>
</body>

</html>

通过代理服务器,我们就避免了跨域问题

    浏览器----》 start.js--->app.js

/api ---> localhost:4000/

猜你喜欢

转载自blog.csdn.net/qq_15009739/article/details/108101196
今日推荐