将Curl GET请求转换为Ajax

时间:2016-08-19 13:44:29

标签: jquery ajax curl

我尝试复制Curl请求以在Ajax中下载PDF。 Curl请求在PDF填充文档here中进行了解释。以下Curl请求成功生成文件内容的响应:

curl -X "GET" "https://api.pdffiller.com/v1/fillable_template/DOCUMENT_ID/download" -H "Authorization: Bearer API_KEY_FROM_STEP1"

我已尝试过以下Ajax:

$.ajax({
    method: 'GET',
    url: 'https://api.pdffiller.com/v1/fillable_template/DOCUMENT_ID',
    headers: {
      Authorization: 'Bearer API_KEY_FROM_STEP1',
    },
})

产生以下错误消息:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我也尝试了用于标题的xhr,这也给出了同样的错误:

$.ajax({
    method: 'GET',
    url: 'https://api.pdffiller.com/v1/fillable_template/DOCUMENT_ID',
    beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Bearer ' + 'API_KEY_FROM_STEP1');
        xhr.setRequestHeader('Accept-Language', 'en_US');
    },
})

有关我出错的地方的任何想法?谢谢!

1 个答案:

答案 0 :(得分:2)

您还需要在请求中添加CORS标头,因为您想要执行跨域请求。您请求的url也必须允许CORS,但由于它是API调用,因此应该允许他们支持...

$.ajax({
    method: 'GET',
    url: 'https://api.pdffiller.com/v1/fillable_template/74275400',
    crossDomain: true,
    xhrFields: {
        withCredentials: true
    },
    headers: {
        Authorization: 'Bearer S1qAS0YFCfUbRemx2OGaeUcmm6mni1EXK3T1FkkL',
    },
});