Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am using Web Worker with ReactJS (Context API schema) and facing with this problem.
My Web API and Context was designed as bellow:
WebWorker.js
export default class WebWorker {
constructor(worker) {
let code = worker.toString();
code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}"));
const blob = new Blob([code], { type: "application/javascript" });
return new Worker(URL.createObjectURL(blob));
And custom AppWorker.js
import { axios } from 'axios'
export default function AppWorker(args) {
// eslint-disable-next-line
let onmessage = function (e) {
if (e.data.action === "join_network") {
axios.get('http://example.com/').then(function (response) {
console.log(response);
.catch(function (error) {
console.log(error);
On main component, inside componentDidMount() method
//App Component.js
import WebWorker from '../../core/Workers/WebWorker';
import AppWorker from '../../core/Workers/AppWorker';
componentDidMount() {
//Start worker for stuff here
const workerInstance = new WebWorker(AppWorker);
workerInstance.addEventListener("message", e => {
console.log(e.data);
}, false);
workerInstance.postMessage({
action: "join_network"
I've been told that we can call API method in Web worker, but when I ran the script, this error shown (see the attached link).
Anyone here get the problem ?
edit: add link: https://pastebin.com/9jRn25Ek
https://i.stack.imgur.com/sJOuZ.jpg
–
I realise this is a late answer, but better late than never. You're not importing Axios properly, hence the reference error. You're attempting to import a single export from the Axios library that doesn't exist. In your AppWorker.js
file, change the import to:
import axios from 'axios'
This will import the default export from the Axios library and you'll good to go.
–
This is normal case. Even if you import axios
in AppWorker
them have a different execute context.
In webworker executing AppWorker
doesn't use axios
.
You can import cdn of axios package in Webworker
Using jsDelivr CDN:
self.importScripts('https://npmcdn.com/axios/dist/axios.min.js')
Using unpkg CDN:
self.importScripts('https://unpkg.com/axios/dist/axios.min.js')
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.