最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot upload worker script using Cloudflare API: Main module name is not present in bundle - Stack Overflow

programmeradmin4浏览0评论

I'm trying to use this API route of the Cloudflare API to upload a worker with metadata.

I'm using Node.js 18 and Axios 0.29, with the following code:

  const api = axios.create({
      baseURL: '',
      headers: {
        Authorization: `Bearer ${myToken}`,
        'Content-Type': 'multipart/form-data',
      },
  })


  const workerCode = `export default {
  async fetch(request, env, ctx) {
    return new Response("Hello World!");
  },
};`

  const form = new FormData();
  form.append('main.js', workerCode);
  form.append(
    'metadata',
    JSON.stringify({
      main_module: 'main.js',
      compatibility_date: '2025-02-04',
      compatibility_flags: ['nodejs_compat'],
    })
  );

  await api.put(
    `/accounts/${accountId}/workers/scripts/${workerName}`,
    form
  );

The error message is always the same: 10021 - Uncaught TypeError: Main module name is not present in bundle

What am I missing? I cannot find any example in the documentation, but I carefully read the API docs and I cannot make it work.

Copy-pasting the worker code manually in the Cloudflare Dashboard works.

Thanks a lot!

I'm trying to use this API route of the Cloudflare API to upload a worker with metadata.

I'm using Node.js 18 and Axios 0.29, with the following code:

  const api = axios.create({
      baseURL: 'https://api.cloudflare/client/v4',
      headers: {
        Authorization: `Bearer ${myToken}`,
        'Content-Type': 'multipart/form-data',
      },
  })


  const workerCode = `export default {
  async fetch(request, env, ctx) {
    return new Response("Hello World!");
  },
};`

  const form = new FormData();
  form.append('main.js', workerCode);
  form.append(
    'metadata',
    JSON.stringify({
      main_module: 'main.js',
      compatibility_date: '2025-02-04',
      compatibility_flags: ['nodejs_compat'],
    })
  );

  await api.put(
    `/accounts/${accountId}/workers/scripts/${workerName}`,
    form
  );

The error message is always the same: 10021 - Uncaught TypeError: Main module name is not present in bundle

What am I missing? I cannot find any example in the documentation, but I carefully read the API docs and I cannot make it work.

Copy-pasting the worker code manually in the Cloudflare Dashboard works.

Thanks a lot!

Share Improve this question edited yesterday Boris K asked 2 days ago Boris KBoris K 1,5541 gold badge12 silver badges30 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

On this line:

form.append('main.js', workerCode);

You are adding the worker code as a string field, but it needs to be a file instead, with a file name.

Try:

form.append('main.js', new Blob([workerCode]), 'main.js');

See: https://developer.mozilla./en-US/docs/Web/API/FormData/append

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论