【问题标题】:Angular not getting data when browser and postman are当浏览器和邮递员使用时,Angular 没有获取数据
【发布时间】:2019-10-11 10:29:33
【问题描述】:

我有一个在 Django Rest Framework 中开发的 API,它在我的浏览器和邮递员中调用时可以工作,但在 Angular 中调用时会给出“(失败)”响应。不提供响应代码(例如 404)

在控制台日志中,它声称由于 CORS,但同一浏览器允许它然后直接调用。

获取:

Access to XMLHttpRequest at 'http://localhost:8000/article/articletype' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

我从 Django 控制台知道调用成功,因为它给出了 200 响应。

我尝试通过向 Angular 调用添加标头来允许 CORS 从两端绕过。以下是我允许的访问控制。 我也玩过不同的 Content-Types 和 Accepts(是 text/html),但现在列为 *

'Accept' : '*/*' , 'Content-Type': '*' , 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers':'*'

对于 Django,我添加了带有 CORS_ORIGIN_ALLOW_ALL = True 的“corsheaders”插件

我也尝试过在 Django 中返回 JSON 和 JsonResponse 的 HttpResponse。

在 Django RFW 中:

目前代码看起来像这样,但我尝试了很多不同的迭代

jresponse = {
        "id" : 2,
        "text" : response,
        "prev_button" : "...prev",
        "subject1" : "SomeSub",
        "stage" : "SomeStage",
        "type1" : "SomeType1",
        "type2" : "SomeType2",
        "subject_list" : ["Sub1","Sub2","Sub3","Sub4"],
        "stage_list" : ["Stage1","Stage2","Stage3","Stage4"],
        "type1_list" : ["Type1.1","Type1.2", "Type1.3","Type1.4"],
        "type2_list" : ["Type2.1","Type2.2","Type2.3","Type2.4"],
    }

    jr=json.dumps(jresponse)
    jr['Access-Control-Allow-Origin'] = '*'
    jr['Access-Control-Allow-Headers'] = '*'
    # jr = serialize('json', response) # Tried this, didn't work
    # return JsonResponse(jresponse) # Tried this, didn't work
    return HttpResponse(jresponse) # I have also tried returning the 'jr' variable

在我所有的迭代中,我通常会在浏览器中得到响应。

对于 Angular:

  getArticles() { 
    let add = 'http://localhost:8000/page/'.concat(this.articleid);
    this.http.get(add, 
      {headers : { 'Accept' : '*/*' , 'Content-Type': '*' , 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers':'*' }}
      ).subscribe(
      article => { this.article = article;
        console.log(this.article)
      })

如前所述,Accept 和 Content-Type 已经通过工厂。

我希望 Angular 接收我可以在模板中使用的 Json 对象

例如:{{article.subject}}

【问题讨论】:

  • 您是否正确配置了CORS中间件? (在普通中间件之前)
  • GET 请求不执行飞行前 CORS 检查。您问题中的错误是针对“localhost:8000/article/articletype”,但您的代码未访问该 URL

标签: django angular django-rest-framework cors


【解决方案1】:

更新了您的设置,例如:

首先将您的 Angular URL 添加到 allowed hosts

ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'other IP of servers']

然后检查middleware 设置,例如:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

然后添加以下设置:

CORS_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_HEADERS = True
CORS_ORIGIN_ALLOW_ALL = True


CORS_ORIGIN_WHITELIST = (
    'localhost:4200',
    'localhost:8000',
    '127.0.0.1:8000',
    'other IPs'
)

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

CSRF_TRUSTED_ORIGINS = (
    '127.0.0.1:9200',
    'localhost:9200',
    'other IPs'
)

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

我在使用 angular 时遇到了同样的问题,然后我添加了上面的设置,然后它就起作用了。

【讨论】:

  • 实际上不需要将客户端的服务器域添加到允许的主机。它只适用于 Django 服务器
  • 尝试了上述方法没有任何乐趣。
  • 尝试上述方法没有任何乐趣。我还添加了标题: res = HttpResponse(jr) res['Access-Control-Allow-Origin'] = '*' return HttpResponse(jr) 无济于事。与django的握手过程是怎样的?
猜你喜欢
  • 2020-03-26
  • 2021-04-28
  • 2021-05-24
  • 2021-03-10
  • 2020-01-17
  • 2021-09-04
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多