How to make an AJAX-request look like a regular, normal request

亡梦爱人 提交于 2019-12-23 19:51:47

问题


What parameters on a $.ajax must I set to try and mask the AJAX-request as a normal request? I guess it has to do with the right headers.

I think a big part of the problem is that when working on a local .html-file, jQuery sets the header-value for Origin to null.

Is there any way to take out the Origin-header?

At this moment I'm getting different results from the same URL if I surf to it through the web-browser and when I do an jQuery AJAX-request.


回答1:


The only thing that differs in an AJAX request sent with jQuery compared to a normal request (whatever you mean by normal request) is the X-Requested-With: XMLHttpRequest HTTP header that is added. This header could be removed like this:

$.ajax({
    url: '/foo',
    type: 'POST',
    data: { bar: 'baz' },
    beforeSend: function(xhr) {
        xhr.setRequestHeader(
            'X-Requested-With',
            {
                toString: function() { return ''; }
            }
        );
    },
    success: function(result) {
       alert(result);   
    }
});

or globally, for all AJAX requests on your site:

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader(
            'X-Requested-With',
            {
                toString: function() { return ''; }
            }
        );
    }
});



回答2:


Due to Same Origin Policy enforced by all modern browsers, this is not possible.




回答3:


  1. jQuery doesn't set Origin Header. Only browser itself can do it. And jQuery(or javascript) has no power over this header.

  2. here is a link about Origin Header cases set to null Null Origin Header

  3. the only difference between jquery and regular request is indeed X-Requested-With: XMLHttpRequest you can remove it by hand or you can make requests with new XMLHttpRequest, or with fetch().

good luck



来源:https://stackoverflow.com/questions/6432320/how-to-make-an-ajax-request-look-like-a-regular-normal-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!