简体   繁体   中英

Cross-domain request with Jquery 1.10.2

I am making the following request:

function doPoolPartyGetChildrenAjaxRequest(parent) {

return $.ajax({

    url: "http://127.0.0.1:8086/PoolParty/api/thesaurus/1DCE2E49-7DD8-0001-524C-1A1B14A0141A/childconcepts",

    data: {language: "en", parent: parent, properties: "skos:narrower"},

    username: 'xxxx',
    password: 'xxxx',

    dataType: 'json',

    crossDomain: true,


    beforeSend: function (req) {
        req.setRequestHeader('Authorization', 'Basic ' + btoa('superadmin:poolparty'));
    },

    xhrFields: {
        withCredentials: true
    },

    error: function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus);
    },

    success: function (data) {

        for (var i = 0; i < data.length; i++) {
            data[i].title = data[i].prefLabel

            if (!(data[i].narrowers === undefined)) {
                data[i].lazy = true
            }
        }

        data.sort(function(a, b) {

            if (a.prefLabel.toLowerCase() == b.prefLabel.toLowerCase())
                return 0;
            if (a.prefLabel.toLowerCase() > b.prefLabel.toLowerCase())
                return 1;
            else
                return -1

        });

    }
})

What do i need to do to have it working, here is the error that i am getting:

OPTIONS http://127.0.0.1:8086/PoolParty/api/thesaurus/1DCE2E49-7DD8-0001-524C-1A1B …Fthesaurus.iadb.org%2Fpublicthesauri%2FIdBTopics&properties=skos%3Anarrower 401 (Unauthorized) m.ajaxTransport.send
m.extend.ajax doPoolPartyGetChildrenAjaxRequest setPoolPartyTreeBroswer
(anonymous function)
m.Callbacks.j m.Callbacks.k.fireWith
m.extend.ready
J XMLHttpRequest cannot load http://127.0.0.1:8086/PoolParty/api/thesaurus/1DCE2E49-7DD8-0001-524C-1A1B14A0141A/childconcepts?language=en&parent=http%3A%2F%2Fthesaurus.iadb.org%2Fpublicthesauri%2FIdBTopics&properties=skos%3Anarrower . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:63342 ' is therefore not allowed access. The response had HTTP status code 401. error

I don't understand the error well. How can i see if my code is sending the right headers to the server ? How can i see what the server respond.

My Tomcat 7 config is as follows:

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

I don't know what else i have to do. Please can anyone guide me on this.

How can i check things out, what is send receive. Is there anything particular with jquery 1.10.2.

Is there something wrong with the corsfilter of Tomcat 7 ?

I had working in the past with tomcat6. Since then i change to tomcat 7, and it simply does not work.

Are you running Chrome with CORS disabled? Try running from the command line:

google-chrome --disable-web-security

For more information on how to disable web security, check here

You need to set the Access-Control-Allow-Origin response header also to get CORS work

Try

 headers.add("Access-Control-Allow-Origin", "*");

I have done this earlier like this in Spring MVC.

package org.springframework.web.servlet.support;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "*");        
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())); {
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Authorization");        
            response.addHeader("Access-Control-Max-Age", "1728000");
        }
        filterChain.doFilter(request, response);
    }

}

// example web.xml configuration

/*
  <filter>
    <filter-name>cors</filter-name>
    <filter-class>org.springframework.web.servlet.support.CorsFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
*/

I also did what is mentioned here

package com.zhentao;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "1800");//30 min
        }
        filterChain.doFilter(request, response);
    }
}

The web.xml needs adding the following too:

  <filter>
    <filter-name>cors</filter-name>
    <filter-class>com.zhentao.CorsFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM