【问题标题】:$.ajax call in content script throwing 405 error内容脚本中的 $.ajax 调用引发 405 错误
【发布时间】:2016-11-11 19:06:39
【问题描述】:

我期待下面的代码执行 Ajax 调用。但是,我看到一个 405 错误,上面写着

请求的资源不支持 http 方法 'GET'。

如果我使用 type = 'json' 我会得到 ​​p>

请求的资源不支持 http 方法“JSON”。

这是我的内容脚本代码的相关部分

$(document).ready(function() {
            var imgSrcArr = [];
            $('img').each(function(e) {
                var s = this.src;
                imgSrcArr.push(s);

                $.ajaxSetup({cache: false});

                var formData = new FormData();
                formData.append("apikey", "xxxxxxxxxxxxxxx"); 
                formData.append("isOverlayRequired", false);
                formData.append("url", s);              
                //console.log(formData);

                //console.log($.support.cors);
                $.ajax({
                    url: "https://api.ocr.space/parse/image",
                    data: {apikey: "xxxxxxxxxxxxxxx", url: s},
                    //method: 'GET',
                    dataType: 'json',
                    async: false,
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    processData: false,
                    type: 'GET',
                    crossDomain: true,
                    xhrFields: {
                        // The 'xhrFields' property sets additional fields on the XMLHttpRequest.
                        // This can be used to set the 'withCredentials' property.
                        // Set the value to 'true' if you'd like to pass cookies to the server.
                        // If this is enabled, your server must respond with the header
                        // 'Access-Control-Allow-Credentials: true'.
                        withCredentials: true
                    },
                    headers: {
                        // Set any custom headers here.
                        // If you set any non-simple headers, your server must include these
                        // headers in the 'Access-Control-Allow-Headers' response header.
                    },
                    success: function(ocrParsedResult, textStatus, jqXHR) {
                        //Get the parsed results, exit code and error message and details
                        var parsedResults = ocrParsedResult["ParsedResults"];
                        var ocrExitCode = ocrParsedResult["OCRExitCode"];
                        var isErroredOnProcessing = ocrParsedResult["IsErroredOnProcessing"];
                        var errorMessage = ocrParsedResult["ErrorMessage"];
                        var errorDetails = ocrParsedResult["ErrorDetails"];

                        var processingTimeInMilliseconds = ocrParsedResult["ProcessingTimeInMilliseconds"];

                        //If we have got parsed results, then loop over the results to do something
                        if (parsedResults!= null) {
                            //Loop through the parsed results
                            $.each(parsedResults, function (index, value) {
                                var exitCode = value["FileParseExitCode"];
                                var parsedText = value["ParsedText"];
                                var errorMessage = value["ParsedTextFileName"];
                                var errorDetails = value["ErrorDetails"];

                                var textOverlay = value["TextOverlay"];

                                var pageText = '';
                                switch (+exitCode) {
                                    case 1: 
                                        pageText = parsedText;
                                        break;
                                    case 0:
                                    case -10:
                                    case -20:
                                    case -30:
                                    case -99:
                                    default: 
                                        pageText += "Error: " + errorMessage;
                                        break;
                                }

                                console.log(parsedText);


                                var bazExtract = extractEmails1(parsedText);
                                if(bazExtract !== null) {
                                    extractEmails2(bazExtract);
                                }
                            });
                        }
                    },
                    error: function(err) {
                        console.log(err);
                    }
                });
            });
            //console.log(imgSrcArr);
        });

注意:内容脚本代码的其他部分正在按预期运行,但没有对 Ajax 请求的服务器响应(在开发人员控制台中)。

如果这是 CORS 问题,是否有解决此类错误的方法?我尝试了一些关于 SO 类似问题的答案,但我无法继续解决其中任何一个问题。

【问题讨论】:

  • 如果使用contentType: "application/json"processData: false,则不能将对象用作data: 参数。 processData 选项表示不将对象转换为字符串,$.ajax 不知道如何发送 JSON。
  • 如果你使用data: formData,你应该只使用processData: false。然后你应该使用contentType: 'multipart/form-data'
  • @Barmar 嘿,我将contentType 更改为'multipart/form-data',将data 更改为formData,将type 更改为POST,现在我在控制台中看不到任何错误或任何服务器响应。我至少应该能够看到console.log(parsedText)。为什么会这样?
  • 您是否在控制台的“网络”选项卡中看到请求和响应?

标签: jquery ajax google-chrome-extension


【解决方案1】:

API 的documentation 中的标题“发布参数”表明您应该执行 POST,而不是 GET。即使用:type: POST

【讨论】:

  • 同时去掉contentTypeprocessData选项。
  • @Barmar 当我删除contentTypeprocessData 保持type 是'POST' 我得到jQuery.Deferred exception: Illegal invocation TypeError: Illegal invocation 指向$.ajax 行和$('img') 行。仅供参考,我将$('img') 更改为$('img[src *= "mail"]'),这不会影响我现有的代码吧?
  • @SunandoSamaddar 当您这样做时,您有什么data 选项?您上面的评论说您更改为data: formData,在这种情况下您确实需要processData: false
  • @Barmar 对此感到抱歉。这次我正在做data: formDataprocessData: false,但在控制台中又看不到console.log(parsedText) 输出。
猜你喜欢
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2015-07-16
  • 2011-08-11
相关资源
最近更新 更多