Upload Worker Module In Cloudflare

230 Views Asked by At

I have an issue with uploading the worker.js file using Laravel Http class, this is docs link: Upload Worker Module My code

$response = Http::baseUrl(self::BASE_URL)
            ->withHeaders(['Content-Type' => 'multipart/form-data'])
            ->withHeaders($this->getAuthHeaders())
            ->withUrlParameters([
                'account_id' => $this->accountId,
                'worker_name' => $workerName
            ])
            ->withBody(file_get_contents(resource_path('js/worker.js')))
            ->put('accounts/{account_id}/workers/scripts/{worker_name}');

and response is:

 "errors": [
        {
            "code": 10001,
            "message": "workers.api.error.content_type"
        }
    ]

if I tried to replace withBody by attach or change content type to application/javascript+module, the response changed to

 "errors": [
        {
            "code": 10001,
            "message": "Uncaught SyntaxError: Unexpected token 'export'\n at worker.js:1\n"
        }
    ]

I make many searches using google, chatgpt or bard and the same problem with different responses

1

There are 1 best solutions below

0
On

This code solves the problem

    $response = Http::baseUrl(self::BASE_URL)
            ->withHeaders($this->getAuthHeaders())
            ->attach('metadata', json_encode(['main_module' => 'worker.js']), headers: ['Content-Type' => 'application/json'])
            ->attach('file', fopen(resource_path('js/worker.js'), 'r'),headers: ['Content-Type' => 'application/javascript+module'])
            ->withUrlParameters([
                'account_id' => $this->accountId,
                'worker_name' => $workerName
            ])->put('accounts/{account_id}/workers/scripts/{worker_name}');