jQuery ajax GET 返回 405 Method Not Allowed

Posted

技术标签:

【中文标题】jQuery ajax GET 返回 405 Method Not Allowed【英文标题】:jQuery ajax GET returns 405 Method Not Allowed 【发布时间】:2011-09-25 06:35:34 【问题描述】:

我正在尝试访问需要身份验证的 API。这是我正在使用的代码,但我不断收到 405 Method Not Allowed 错误。有什么想法吗? (我的用户名和密码正确)

function basic_auth(user, pass)
    var tok = user + ':' + pass;
    var hash = $.base64.encode(tok);
    return "Basic " + hash;

var auth = basic_auth('username','password');
var releaseName1 = "11.6.3";
var releaseName2 = "11.6.3 Confirmed";
$.ajax(
    type: "GET",
    url: "https://www10.v1host.com/Company/rest-1.v1/Data/Story?sel=Description,Number,Name,Timebox.Name,Parent,AssetState&where=Custom_Release2.Name='"+releaseName1+"','"+releaseName2+"';AssetState='64'",
    beforeSend: function(xhr)
        xhr.setRequestHeader('Authorization', auth);
    ,
    dataType: "xml",
    async: false,
    success: parseXml
);
function parseXml(xml)
    $(xml).find("item");

【问题讨论】:

两个页面在同一个域中? 您的意思是我的带有此代码的页面与其请求的页面在同一个域中吗?如果是这样,那么不,他们不是。 【参考方案1】:

您不能跨域进行 javascript/Ajax 调用(没有一些严重的混乱)。我们过去为此所做的是创建一个本地 jsp 代理,我们使用我们的 javascript 调用它,但它只是对远程 URL 的传递。

这里是一些示例 JSP 代码,它与我用来命中返回 JSON 的 SOLR 实例的代码非常接近。

final String ENCODING = "UTF-8"; // this is the default unless specified otherwise (in server.xml for Tomcat)
    // see http://tomcat.apache.org/tomcat-6.0-doc/config/http.html#Common_Attributes and
    // http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q2
    final String URI_ENCODING = "ISO-8859-1";

    HashMap<String, String> defaultSettings = new HashMap<String, String>() 
        
            put("wt", "json");
            put("rows", "10");
            put("start", "0");
        
    ;

    BufferedReader searchResponse = null;
    OutputStreamWriter forwardedSearchRequest = null;

    // TODO:  are there any headers that we need to pass on?
    // simply pass on the request to the search server and return any results
    try 
        URL searchURL = new URL("http://yourdestinationurlhere.com");
        HttpURLConnection conn = (HttpURLConnection) searchURL.openConnection();

        // read the request data and send it as POST data (unchanged)
        conn.setDoOutput(true);
        forwardedSearchRequest = new OutputStreamWriter(conn.getOutputStream());

        // at least for Tomcat 6.0, the default is really iso-8859-1, although it is reported as UTF-8
        // so, we will explicitly set it to URI_ENCODING in both places
        request.setCharacterEncoding(URI_ENCODING);

        String query = (String) request.getParameter("q");
        if ((query != null) && (! "".equals(query.trim()))) 
            query = URLEncoder.encode(query, request.getCharacterEncoding()); // we must use the same setting as the container for URI-encoding
            forwardedSearchRequest.write("&q=");
            forwardedSearchRequest.write(query);
         else 
            // empty queries may return all results, so let's circumvent that
            forwardedSearchRequest.write("&q=help");
        

        for(String key:defaultSettings.keySet()) 
            String resultType = (String) request.getParameter(key);
            if ((resultType == null) || "".equals(resultType.trim())) resultType = defaultSettings.get(key);
            forwardedSearchRequest.write("&"+key+"=");
            forwardedSearchRequest.write(resultType);
        

        forwardedSearchRequest.flush();

        // read and forward the response
        // reset anything that may have been sent so far
        out.clearBuffer();

        // do this only if we have a 200 response code
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) 
            // the web server may be running as windows-1252, so let's ensure we have the right CS
            searchResponse = new BufferedReader(new InputStreamReader(conn.getInputStream(), ENCODING));

            String contentType = conn.getHeaderField("Content-Type");
            if ((contentType != null) && (! "".equals(contentType))) response.setHeader("Content-Type", contentType);

            String buffer;
            while ((buffer = searchResponse.readLine()) != null) out.println(buffer);
         else 
            // dish out a mock-Solr-JSON response that includes a status and an error
            response.setHeader("Content-Type", "application/json");
            out.println(" responseHeader: status: -1, responseCode: " + conn.getResponseCode()  +
                ", responseMessage: \"" + conn.getResponseMessage() + "\"  ");
        
     catch (Exception e) 
        throw new ServletException("Exception - " + e.getClass().getName(), e);
     finally 
        if (forwardedSearchRequest != null) forwardedSearchRequest.close();
        if (searchResponse != null) searchResponse.close();
    

【讨论】:

这听起来像是一个选项...你有例子吗? @RyanPitts 你有机会尝试一下吗?它对你有用吗? 我发现我的问题是AJAX不能进行跨域调用。我通过 php 解决了这个问题。我使用 PHP 的 cUrl 获取数据并将其打印出来,然后使用 jQuery AJAX 调用保存返回数据的 PHP 页面。不过感谢您的帮助! 我相信这正是我所说和建议的!很高兴一切顺利。【参考方案2】:

如果您正在尝试发送跨域请求,请尝试将您的数据类型更改为“jsonp”

【讨论】:

以上是关于jQuery ajax GET 返回 405 Method Not Allowed的主要内容,如果未能解决你的问题,请参考以下文章

jQuery .ajax() POST 请求抛出 405(不允许的方法)但 GET 不会

HTTP 错误 405.0 - 不允许使用 Jquery ajax get 的方法

Laravel 5.1 AJAX - 即使我发送 POST 请求,也不允许返回 405 GET 方法

JQuery Ajax POST 到 Web API 返回 405 Method Not Allowed

Laravel:使用 jquery ajax api 发布数据来存储数据时获取 405 Method Not Allowed

Ajax POST / Nginx 配置出现 405 错误