'Request header field Authorization is not allowed' error - Tastypie

前端 未结 5 1107
感情败类
感情败类 2020-12-30 22:31

I am getting the following error while using ApiKeyAuthentication for my Tastypie resources when I try to do an HTTP request using AJAX and Tastypie:

XMLHttp         


        
5条回答
  •  囚心锁ツ
    2020-12-30 23:21

    Although I upvoted the answer of @Manuel Bitto,
    I would like to post another answer which contains a complete Cors Filter that works for me with Apache tomcat 5.x:

    public class CorsFilter implements Filter {
    
        public CorsFilter() { }
    
        public void init(FilterConfig fConfig) throws ServletException { }
    
        public void destroy() { }
    
        public void doFilter(
    
                ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            HttpServletResponse httpServletResponse = (HttpServletResponse)response;
            httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS, DELETE");
            httpServletResponse.addHeader("Access-Control-Allow-Headers", "Authorization");
    
            chain.doFilter(request, response);
        }
    }
    

    I would suggest to specifically pay attention to the addition of OPTIONS to to the "Access-Control-Allow-Methods" header values.
    The reason for doing that is that according to the explanation provided here by Mozilla,
    if your request (let's say POST) contains a special header, or content type (and this is my case), then the XMLHttpRequest object will generate an additional OPTIONS call, which you need to address in your code.
    I hope this helps.

提交回复
热议问题