weixin_33675507 2017-07-18 20:46 采纳率: 0%
浏览 158

Django jquery ajax cors错误

I get this error in the console when I try to post data with ajax. This data is supposed to be confirmed at this url and then I should get a response from it containing more data.

Cross-Origin Request Blocked: The Same Origin Policy disallows 
reading the remote resource at https://secure.paygate.co.za/payweb3/process.trans. 
(Reason: CORS header 'Access-Control-Allow-Origin'  missing).

I am using django-cors-headers as middleware to add the headers. I followed all the config instructions.

My settings.py:

INSTALLED_APPS = [
    # ...
    'corsheaders',
    # ...
]

MIDDLEWARE = [
    # ...
    'corsheaders.middleware.CorsMiddleware',
    # ...
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
    'GET',
    'POST',
    'OPTIONS',
)

The ajax call:

$.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: data,
        success: function(data){
            alert('success');
        },
        error: function(data){
            alert('error');
        }
    });

The data and url is declared above this and that part is fine. I only get the error alert everytime I submit it.

My packages:

Django==1.11.3
django-cors-headers==2.1.0
pytz==2017.2

I am on Windows 10.

EDIT: I added the csrfSafeMethod for ajax. I don't know if this might have something to do with it?. This code is provided by djangoproject here docs.djangoproject.com/en/1.11/ref/csrf

EDIT2: I ended up sending an ajax call internally so then I did the cross domain stuff with django using urllib. This helped me a lot with posting data cross domain.

  • 写回答

1条回答 默认 最新

  • weixin_33701617 2017-07-19 13:05
    关注

    As per the documentation:

    CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware or Whitenoise's WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

    I would recommend you to put it as the first middleware (highest) among all the present middlewares.

    Reference: https://github.com/ottoyiu/django-cors-headers

    评论

报告相同问题?