首页 > 解决方案 > 来自 DOM 的代理 webpack-dev-server

问题描述

我想index.html在本地应用程序的初始加载中添加 fetch 调用。否则,此数据会在服务器端加载,但对于这种特殊情况,我需要在 dev 中进行 http 调用。

我在将 fetch 添加到 DOM 的情况下代理 webpack-dev-server 时遇到了困难。

我的应用程序被实例化并且我使用 Axios对/api.

这让我有点困惑——为什么代理可以在 JS 加载后工作,但不能在 init 上工作?

devServer: {
    contentBase: '/some/path',
    port: 9000,
    https: true,
    open: true,
    compress: true,
    hot: true,
    proxy: { '/api/*': [Object] }
  },

索引中的脚本

  <script>
      (async function() {
        const data = await getData();
        addDataset(data);

        async function getData() {
          return fetch('/api/my/endpoint').then(
            (response) => response.data.result,
          );
        }

        function addDataset(data) {
          var el = document.getElementById('root');
          const parsed = JSON.parse(data);
          Object.entries(parsed).forEach((entry) => {
            const [k, val] = entry;
            el.dataset[k] = JSON.stringify(val);
          });
        }
      })();
    </script>

错误

400 Bad request 
Request URL - https://localhost:9000/api/my/endpoint

标签: fetchwebpack-dev-server

解决方案


推荐阅读