javascript - 使用 Node.js 中的 API 调用清除 Cloudflare 缓存

标签 javascript node.js request cloudflare

我希望通过其 API 清除 Cloudflare 的缓存.更具体地说,purge all files命令。

但是,尽管显式设置了 Content-Type,但我一直遇到 “无效的 Content-Type header ,有效值为 application/json,multipart/form-data” 错误消息 header 与 Node.js 的 request包。

我错过了什么?


var request = require('request');

gulp.task('cfPurge', function() {

    var options = {
        url: 'https://api.cloudflare.com/client/v4/zones/myZoneID/purge_cache',
        headers: {
            'X-Auth-Email': 'email',
            'X-Auth-Key': 'myAPIkey',
            'Content-Type': 'application/json'
        },
        form: {
            'purge_everything': true,
        }
    };

    function callback(error, response, body) {
        var resp = JSON.parse(body);

        if (!error & response.statusCode == 200) {
            console.log('CF Purge: ', resp.success);
        }
        else {
            console.log('Error: ', resp.errors);
            for (var i = 0; i < resp.errors.length; i++)
                console.log('      ', resp.errors[i]);

            console.log('Message: ', resp.messages);
            console.log('Result: ', resp.result);
        }
    }

    return request.post(options, callback);
});

输出:

Error:  [ { code: 6003,
    message: 'Invalid request headers',
    error_chain: [ [Object] ] } ]
       { code: 6003,
  message: 'Invalid request headers',
  error_chain:
   [ { code: 6105,
       message: 'Invalid Content-Type header, valid values are application/json,multipart/form-data' } ] }
Message:  []
Result:  null

最佳答案

根据documentation对于 cloudfare API,您需要发送 HTTP DELETE 请求而不是 HTTP POST 请求:

enter image description here

修改行...

return request.post(options, callback);

...与:

return request.del(options, callback);

此外,这不是表格。您需要将 JSON 放在数据正文中。所以,更换 block ...

form: {
    'purge_everything': true,
}

...与:

body: JSON.stringify({'purge_everything': true})

关于javascript - 使用 Node.js 中的 API 调用清除 Cloudflare 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454175/

相关文章:

javascript - 我如何解析 ng-repeat 内的数组(来自函数)

javascript - 在对象函数中定义 getter/setter

jquery - 将新的键值对推送到 json

javascript - Node.js 中依赖于版本的类型继承

javascript - 发布请求抛出 net::ERR_HTTP2_PROTOCOL_ERROR

javascript - 如何在 RoR 4 中向浏览器发送 DELETE 请求

javascript - 如何查找文档中是否存在元素 - MongoDB?

ios - Alamofire 请求错误 - SWIFT 2.0

amazon-web-services - 从 AWS EC2 元数据链接本地地址获取多个项目

javascript - 更改输入值或添加新输入(如果不存在)