Proxy webpack-dev-server from the DOM

Viewed 255

I want to add a fetch call to the initial load of index.html on a local app. This data is otherwise loaded server-side, but for this particular case I need to make an http call in dev.

I am having difficulty proxying the webpack-dev-server with the fetch added to the DOM.

The proxy is working correctly after my app is instantiated and I use Axios to make http calls to /api, but on init, the proxy is still serving from localhost instead of the target endpoint.

This is a bit puzzling to me - why might the proxy work in JS post-load but not on init?

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

Script in index

  <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>

Error

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