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

    评论

报告相同问题?

悬赏问题

  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机