繁体   English   中英

如何在带有 vue 的 web worker 中使用 axios?

[英]How use axios in web worker with vue?

我已经尝试通过vue 插件在 web worker 中使用 axios 请求

我的代码如下所示:

//worker.js

import axios from 'axios';

export default function getApiData (args) {
    axios.get('/api/test').then(response => {
        console.log(response);
    });
}

和 Vue 的主文件

//main.js

import getApiData from './worker.js';

Vue.use(VueWorker);

window.vueApp = new Vue({
    //...
    created: function () {
        this.updateWorker = this.$worker.create([
            {
                message: 'getApiData ',
                func: getApiData 
            }
        ]);

        this.testWorker.postMessage('getApiData ', [this.args])
            .then(result => {
                console.log(result);
            })
    },
    //...
}

我得到了这个错误

未捕获的 ReferenceError: axios__WEBPACK_IMPORTED_MODULE_0___default 未定义

我做错了什么?

我遇到了同样的问题,并通过回到基础来解决它 - 使用普通的旧 XMLRequest(见下文)。

您不能在 worker 中使用 axios,因为在后台创建的用于加载worker.js的 blob 运行在与您的main.js不同的上下文中。 为了让 axios 工作,你必须设置一个新的 webpack bundler 来单独捆绑 worker。 我不想这样做 - 它使项目结构变得不必要复杂。

这是一个简单的解决方案(适用于 json 和非 json 响应)。

// worker.js

export default () => {
  self.addEventListener('message', e => {
    if (!e) return;

    // wrap in try/catch if you want to support IE11 and older browsers
    // that don't support Promises. The implementation below doesn't work
    // even when polyfills are loaded in the main project because
    // the worker runs in a different context, ie no webpack bundles here.
    try {
      const fetchData = (url, isJSON = true) => {
        return new Promise((resolve, reject) => {
          function reqListener() {
            if (this.status !== 200) {
              return reject();
            }
            const response = isJSON
              ? JSON.parse(this.responseText)
              : this.responseText;
            resolve(response);
          }
          const oReq = new XMLHttpRequest();
          oReq.addEventListener('load', reqListener);
          oReq.open('GET', url);
          oReq.send();
        });
      };

      const baseUrl = 'https://static.newsfilter.io/';
      const { articleId } = e.data;


      const jsonUrl = baseUrl + articleId + '.json';
      const htmlUrl = baseUrl + articleId + '.html';

      // My use case requires 2 requests in parallel. 
      const tasks = [fetchData(jsonUrl), fetchData(htmlUrl, false)];

      Promise.all(tasks)
        .then(data => {
          postMessage({ json: data[0], html: data[1] });
        })
        .catch(error => {
          postMessage({ isError: true, error });
        });
    } catch (error) {
      postMessage({ isError: true });
    }
  });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM