【问题标题】:Django response giving CORS error for an AJAX requestDjango 响应为 AJAX 请求提供 CORS 错误
【发布时间】:2021-06-01 04:25:51
【问题描述】:

我是 Django 和 WordPress 的初学者,我正在从添加到我的 WordPress 页面的 HTML-Javascript 代码发出 API 请求。 API 请求已在 Django-rest-framework 后端成功发送和处理,但响应给我 CORS 错误

控制台错误

从源“http://localhost”访问“http://127.0.0.1:8000/videogen/”处的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头在请求的资源上。

POST http://127.0.0.1:8000/videogen/ net::ERR_FAILED 发送@jquery-3.5.1.min.js:2 ajax@jquery-3.5.1.min.js:2 paraSubmit@(索引):373 onsubmit @ (index):435

XHR 加载失败:POST "http://127.0.0.1:8000/videogen/"。发送 @ jquery-3.5.1.min.js:2 ajax @ jquery-3.5.1.min.js:2 paraSubmit @ (索引):373 onsubmit @(索引):435

我的 WORDPRESS 页面中的 HTML 代码块

<script>
function paraSubmit(event){
event.preventDefault();

 // creating JSON data to send..

$.ajax({
  url : 'http://127.0.0.1:8000/videogen/',
  type: "POST",
  crossDomain: true,
  data: data,
  dataType   : "json",
  success    : function(response){
      console.log(response);
      alert("Video generated and sent!!");
  },
  error : function(response){
      console.log(response);
    //   alert("Video not created" );
  }
  });
}

</script>



<form onsubmit="paraSubmit(event)" id="paragraph-form" >
    <input type="text" id="para-name" name="name" placeholder="Name" required/>
    <input type="text" id="para-email" name="Email" placeholder="Email" required/>
    <textarea id="paragraph" placeholder="Enter Paragraph here" required></textarea>
    <button type="submit" class="btn btn-small">Submit</button>
</form>

Django 后端的settings.py

CORS_ALLOWED_ORIGIN_REGEXES = [
r"^http://127.0.0.1:[0-9]{1,4}$",
r"^https://127.0.0.1:[0-9]{1,4}$"
]

请求被处理,结果在后端成功生成。 响应从后端发送,状态码为 201。

在控制台上打印响应

status: 0 
statusCode: ƒ (e) 
statusText: "error"

请帮我解决这个错误。 如果您需要其他任何东西,请告诉我。

【问题讨论】:

    标签: django ajax wordpress django-rest-framework


    【解决方案1】:

    你需要使用这个 django 库

    https://pypi.org/project/django-cors-headers/

    安装它,然后在settings.py你的应用程序的url中添加

    CORS_ALLOWED_ORIGINS = [
        "https://example.com",
        "http://localhost:5000"
    ]
    

    注意:如果您不使用端口 80 (HTTP) 或 443 (HTTPS),则需要特别包含端口号。

    【讨论】:

    • 我已经在使用它了,但我仍然收到错误。
    • 这个解决方案对我有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2014-05-26
    • 1970-01-01
    • 2012-07-17
    • 2023-03-21
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多