如何在带有Vue的Web Worker中使用axios?

时间:2019-02-22 13:39:22

标签: vue.js axios web-worker

我尝试通过vue plugin

在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为   未定义

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并通过使用简单的旧XMLRequest(请参阅下文)回到基础知识来解决了这个问题。

您不能在worker内部使用axios,因为在后台创建的用于加载worker.js的blob在与main.js不同的上下文中运行。为了使axios能够正常工作,您必须设置一个新的webpack捆绑程序,使其仅捆绑工作程序。我不想这样做-这使项目结构变得不必要的复杂。

这是一个简单的解决方案(适用于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 });
    }
  });
};