【问题标题】:I'm getting Error 203 at Angular to connect at Django Rest Api我在 Angular 上收到错误 203 以连接 Django Rest Api
【发布时间】:2019-11-18 10:21:19
【问题描述】:

我需要帮助来解决问题。我正在开发一个简单的联系人系统,但列出它们时遇到了一些错误。在 Postman,我可以使用 api 进行 CRUD。

在服务器中我收到这条消息:

[2019 年 7 月 8 日 18:25:35] "GET /api/contato/HTTP/1.1" 200 230

这是我的 contato.service.ts

import { Injectable } from '@angular/core'; import { environment } from '../../environments/environment'; import { HttpClient } from '@angular/common/http'; import { Contato } from '../interfaces/contato'; import { Observable } from 'rxjs';

@Injectable({   providedIn: 'root' }) export class ContatoService {

  constructor(private http: HttpClient) { }

  getListaContatos(): Observable <Contato[]> {
    const url = `${environment.contatoApiUrl}/contato/`;
    return this.http.get<Contato[]>(url);   }

  getContato(id: number): Observable <Contato[]> {
    const url = `${environment.contatoApiUrl}/contato/${id}`;
    return this.http.get<Contato[]>(url);   }

  addContato(contato: Contato): Observable <Contato[]> {
    const url = `${environment.contatoApiUrl}/contato/`;
    return this.http.post<Contato[]>(url, contato);   }

  atualizaContato(contato: Contato): Observable <Contato[]> {
    const url = `${environment.contatoApiUrl}/contato/${contato.id}`;
    return this.http.put<Contato[]>(url, contato);   }

  deletaContato(id: number): Observable <Contato[]> {
    const url = `${environment.contatoApiUrl}/contato/${id}`;
    return this.http.delete<Contato[]>(url);   }

}

这是我的 lista-contato.component.ts

import { Component, OnInit, ViewChild } from '@angular/core'; import { Contato } from '../../interfaces/contato'; import { ContatoService } from '../../services/contato.service'; import { ErrorMsgComponent } from '../../compartilhado/error-msg/error-msg.component';

@Component({   selector: 'app-lista-contato',   templateUrl: './lista-contato.component.html',   styleUrls: ['./lista-contato.component.css'] }) export class ListaContatoComponent implements OnInit {   public contatos: Contato[];   @ViewChild(ErrorMsgComponent, {static: false}) errorMsgComponent: ErrorMsgComponent;

  constructor(private contatoService: ContatoService) { }

  ngOnInit() {
    this.getListaContatos();   }

  getListaContatos() {
    this.contatoService.getListaContatos()
      .subscribe((contatos: Contato[]) => {
        this.contatos = contatos;
      }, () => { this.errorMsgComponent.setError('Falha ao buscar contatos.' ); });   }

  deletaContato(id: number) {
    this.contatoService.deletaContato(id)
      .subscribe(() => {
        this.getListaContatos();
      }, () => { this.errorMsgComponent.setError('Falha ao deletar contatos.'); });   }

  existemContatos(): boolean {
    return this.contatos && this.contatos.length > 0;   }

}

来自控制台的错误

ListaContatoComponent.html:8 错误类型错误:无法读取属性 未定义的“id” 在 Object.eval [作为 updateDirectives] (ListaContatoComponent.html:12) 在 Object.debugUpdateDirectives [as updateDirectives] (core.js:39358) 在 checkAndUpdateView (core.js:38370) 在 callViewAction (core.js:38736) 在 execComponentViewsAction (core.js:38664) 在 checkAndUpdateView (core.js:38377) 在 callViewAction (core.js:38736) 在 execEmbeddedViewsAction (core.js:38693) 在 checkAndUpdateView (core.js:38371) 在 callViewAction (core.js:38736) View_ListaContatoComponent_0@ListaContatoComponent.html:8

其他错误:

从 'http://127.0.0.1:8000/api/contato/' 访问 XMLHttpRequest 来源“http://127.0.0.1:4200”已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

【问题讨论】:

  • 你看过203 status code是什么意思吗?你说你得到错误,那些错误是什么?
  • 抱歉我的第一篇文章。
  • 是的,我看到了 203 状态码的意思,但我不知道为什么。
  • 您似乎遇到了一些单独的问题。我先看看@Noremac 的建议。

标签: angular typescript django-rest-framework


【解决方案1】:

您的 Django API 必须允许来自 http://127.0.0.1:4200 的请求。查看Django's documentation on CORS 了解如何操作。您可能还想知道,what is CORS?

【讨论】:

    【解决方案2】:

    您需要使用 cors,就像 @Noremac 所说的那样。来自documenation的一个例子!你如何在 Django 中做到这一点。

    使用命令pip install django-cors-headers安装cors。

    然后在您的 settings.py 文件中将其添加到 INSTALLED_APPS 中:

    INSTALLED_APPS = [
        # I assume there are some other apps here...
        'corsheaders',
    ]
    

    然后在你的中间件中:

    MIDDLEWARE  = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'corsheaders.middleware.CorsMiddleware',
        # others middlewares bellow
    ] 
    

    注意上面的那个,因为带有corsheaders的行需要在任何可以产生响应的中间件之前,比如CommonMiddleware等,documentation about it here!。
    然后在 settings.py 的末尾你可以添加CORS_ORIGIN_ALLOW_ALL = True 或者添加你想要的原点:

    CORS_ORIGIN_WHITELIST = (
        '127.0.0.1:8000'
    )
    

    【讨论】:

      【解决方案3】:

      控制台谷歌浏览器出错

      ListaContatoComponent.html:8 ERROR TypeError: Cannot read property 'id' of undefined
          at Object.eval [as updateDirectives] (ListaContatoComponent.html:12)
          at Object.debugUpdateDirectives [as updateDirectives] (core.js:39358)
          at checkAndUpdateView (core.js:38370)
          at callViewAction (core.js:38736)
          at execComponentViewsAction (core.js:38664)
          at checkAndUpdateView (core.js:38377)
          at callViewAction (core.js:38736)
          at execEmbeddedViewsAction (core.js:38693)
          at checkAndUpdateView (core.js:38371)
          at callViewAction (core.js:38736)
      View_ListaContatoComponent_0 @ ListaContatoComponent.html:8
      

      从 'http://127.0.0.1:8000/api/contato/' 访问 XMLHttpRequest 来源“http://127.0.0.1:4200”已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

      【讨论】:

      • 我用此信息更新了您的原始问题。让您知道将来您可以通过选择问题下方的灰色“编辑”小文本来添加/编辑您的问题。您应该删除此信息作为答案,因为这是此类信息的错误位置。
      【解决方案4】:

      非常感谢,辛苦了。

      但正确的语法是:

      CORS_ORIGIN_WHITELIST = [
           "http://127.0.0.1:4200" ]
      

      而关于“ERROR TypeError: Cannot read property 'id' of undefined”的问题,是因为该属性不在FOR中。

      现在好了..

      谢谢

      【讨论】:

        猜你喜欢
        • 2018-12-11
        • 2016-09-10
        • 2019-01-25
        • 2022-10-15
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多