cloudflare / node-cloudflare

Node.js API for Client API
https://cloudflare.github.io/node-cloudflare/
Other
335 stars 92 forks source link

Purge cache : Bad Request with lib, works with curl #118

Closed OriaLogic closed 7 months ago

OriaLogic commented 1 year ago

Hi,

I have a bug when trying to purge cache for a list of files.

First I test the endpoint with curl :

curl -X POST "https://api.cloudflare.com/client/v4/zones/<DNS_ZONE_ID>/purge_cache" \
     -H "Authorization: Bearer <MY_TOKEN>" \
     -H "Content-Type: application/json" \
     --data '{"files":["http://www.example.com/css/styles.css"]}'

# Response
{"success":true,"errors":[],"messages":[],"result":{"id":"<DNS_ZONE_ID>"}}

I do the exact same thing with the library and I get :

{
  host: 'api.cloudflare.com',
  hostname: 'api.cloudflare.com',
  method: 'POST',
  path: '/client/v4/zones/<DNS_ZONE_ID>/purge_cache',
  statusCode: 400,
  statusMessage: 'Bad Request'
}

I dug into the library to follow the request and log a few things. The parameters for the http call are the following :

// endpoint : https://api.cloudflare.com/client/v4/zones/<DNS_ZONE_ID>/purge_cache 
{
  json: true,
  timeout: 10000,
  retries: undefined,
  method: 'POST',
  headers: {
    'user-agent': 'cloudflare/2.9.1 node/14.17.0',
    'Content-Type': 'application/json',
    Accept: 'application/json',
    'X-Cloudflare-Client-User-Agent': '{"bindings_version":"2.9.1","lang":"node","lang_version":"v14.17.0","platform":"darwin","arch":"x64","publisher":"cloudflare"}',
    Authorization: 'Bearer <MY_TOKEN>'
  },
  body: { files: [ 'http://www.example.com/css/styles.css' ] }
}

I don't understand what is going on here. To me the request is correct, everything seems fine and yet my call does not work

Am I missing something ?

Thanks for the help, Lucas

OriaLogic commented 1 year ago

Ok I was able to make it work by doing

await cf.zones.purgeCache(site.cloudflareZoneId, '{ "files": ["http://example.com/salut.jpg"] }');

Another better way :

 await this.cf.zones.purgeCache(
  this.site.cloudflareZoneId,
  JSON.stringify({ files: imageUrls })
);

but how come I need to turn the parameters into a string in order to make it work ? I must be missing something here...