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

标签 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);
            })
    },
    //...
}

我得到了这个错误

Uncaught ReferenceError: axios__WEBPACK_IMPORTED_MODULE_0___default is not defined



我做错了什么?

最佳答案

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

您不能在 worker 内部使用 axios,因为在后台创建的 blob 用于加载 worker.js在与您的 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 });
    }
  });
};

关于vue.js - 如何在带有 vue 的 web worker 中使用 axios?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54828368/

相关文章:

vue.js - 在 ScriptTransformer._transformAndBuildScript 运行 jest got "Unexpected string"

javascript - 努克斯 : how do I access axios within the fetch() method?

javascript - Vue.js - 渲染组件时出错

node.js - 无法在NodeJS中解决: 'TypeError: Converting circular structure to JSON'

reactjs - .NET webapi 端点在 Postman 中工作,但 Chrome 给出了 net::ERR_FAILED

javascript - 从本地文件系统提供的 Webworker 不工作

node.js - 在使用app的 Electron 应用程序内部使用Webworker

javascript - 如何在 worker 中处理三个网眼对象

vue.js - 如何将 <a href ="/main/@{{item.id}}"> 切换为 v-bind :href in Vue2. 0?

javascript - 未找到 uws - 使用 SocketIO 的 VueJS