本文介绍了jQuery的AJAX GET返回405不允许的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图访​​问要求认证的API。这是我现在用的是code,但我不断收到405不允许的方法错误。有什么想法吗? (我的用户名和密码是正确的)

 函数basic_auth(user和pass){
    VAR TOK =用户+:+通过;
    VAR哈希= $ .base64.en code(TOK);
    返回基本+散;
}
VAR AUTH = basic_auth(用户名,密码);
VAR releaseName1 =11.6.3;
VAR releaseName2 =11.6.3确认;
$阿贾克斯({
    键入:GET,
    网址: "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:功能(XHR){
        xhr.setRequestHeader('授权',验证);
    },
    数据类型:XML,
    异步:假的,
    成功:parseXml
});
功能parseXml(XML){
    $(XM​​L).find(项目);
}
 

解决方案

您不能进行的JavaScript / AJAX跨域调用(不包括一些严重kludging)。我们已经为这个在过去做的是创建一个本地jsp的代理,我们与我们的JavaScript调用,但只是一个传递到远程URL。

下面是一些例子JSP code是接近我已经用打一个SOLR实例返回JSON。

 最后字符串编码=UTF-8; //这是默认的,除非(Tomcat的server.xml中)另有规定
    //看到http://tomcat.apache.org/tomcat-6.0-doc/config/http.html#Common_Attributes和
    // http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q2
    最后弦乐URI_ENCODING =ISO-8859-1;

    HashMap的<字符串,字符串> defaultSettings =新的HashMap<字符串,字符串>(){
        {
            把(重量,JSON);
            把(行,10);
            放(开始,0);
        }
    };

    BufferedReader中searchResponse = NULL;
    OutputStreamWriter forwardedSearchRequest = NULL;

    // TODO:在那里,我们需要传递的任何头?
    //简单的传递请求到搜索服务器和返回任何结果
    尝试 {
        URL searchURL =新的URL(http://yourdestinationurlhere.com);
        HttpURLConnection的康恩=(HttpURLConnection类)searchURL.openConnection();

        //读取请求数据并将其发送的POST数据(不变)
        conn.setDoOutput(真正的);
        forwardedSearchRequest =新OutputStreamWriter(conn.getOutputStream());

        //至少为Tomcat 6.0,默认是真的ISO-8859-1,虽然它被报告为UTF-8
        //所以,我们将明确地将它设置为URI_ENCODING在这两个地方
        request.setCharacterEncoding(URI_ENCODING);

        查询字符串=(字符串)的request.getParameter(Q);
        如果((查询=空)及!&安培;!(.equals(query.trim()))){
            查询= URLEn coder.en code(查询,request.getCharacterEncoding()); //我们必须使用相同的设置作为容器的URI编码
            forwardedSearchRequest.write(与& Q =);
            forwardedSearchRequest.write(查询);
        } 其他 {
            //空的查询可能返回所有结果,让我们规避
            forwardedSearchRequest.write(&放大器; Q =帮助);
        }

        对于(字符串键:defaultSettings.keySet()){
            字符串与resultType =(字符串)的request.getParameter(密钥);
            如果((与resultType == NULL)||.equals(resultType.trim()))与resultType = defaultSettings.get(密钥);
            forwardedSearchRequest.write(与&+键+=);
            forwardedSearchRequest.write(与resultType);
        }

        forwardedSearchRequest.flush();

        //读取并转发响应
        //重置,可能已被发送为止的任何
        out.clearBuffer();

        //做到这一点,只有当我们有一个200响应code
        如果(conn.getResponse code()== HttpURLConnection.HTTP_OK){
            // Web服务器可能正在运行的窗口1252,让我们确保我们拥有正确的CS
            sea​​rchResponse =新的BufferedReader(新的InputStreamReader(conn.getInputStream(),编码));

            字符串的contentType = conn.getHeaderField(内容类型);
            如果((的contentType = NULL)及!及(.equals(的contentType))response.setHeader!)(内容类型,则contentType);

            字符串缓冲区;
            而((缓冲液= searchResponse.readLine())!= NULL)通过out.println(缓冲液);
        } 其他 {
            //盘出一个模拟的Solr JSON的响应,包括状态和错误
            response.setHeader(内容类型,应用/ JSON);
            通过out.println({responseHeader:{状态:-1,响应code:+ conn.getResponse code()+
                ,responseMessage:\+ conn.getResponseMessage()+\}});
        }
    }赶上(例外五){
        抛出新的ServletException异常(异常 - + e.getClass()的getName(),E。);
    } 最后 {
        如果(forwardedSearchRequest!= NULL)forwardedSearchRequest.close();
        如果(!searchResponse = NULL)searchResponse.close();
    }
 

I am trying to access an API that requires authentication. This is the code that i am using but i keep getting a 405 Method Not Allowed error. Any thoughts? (my username and password are correct)

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");
}
解决方案

You can't make javascript/Ajax calls across domains (without some serious kludging). What we've done for this in the past is to create a local jsp proxy that we call with our javascript but is just a pass-through to the remote URL.

Here is some example JSP code that is close to what I've used to hit a SOLR instance returning JSON.

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();
    }

这篇关于jQuery的AJAX GET返回405不允许的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 05:39