Encountering Error 203 while trying to establish a connection between Angular and Django Rest Api

I'm currently working on a project that involves creating a contacts system, but I've been encountering errors when trying to list them. Interestingly, I can successfully perform CRUD operations using Postman with the API.

One of the messages I receive from the server is:

[08/Jul/2019 18:25:35] "GET /api/contato/ HTTP/1.1" 200 230

Inquiry about 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);   }

  // other functions omitted for brevity

}

About 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;

  // code snippet skipped

}

Error Encountered in Console

ListaContatoComponent.html:8 ERROR TypeError: Cannot read property 'id' of undefined at Object.eval [as updateDirectives] (ListaContatoComponent.html:12) // more error details here View_ListaContatoComponent_0 @ ListaContatoComponent.html:8

Another Issue:

Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Answer №1

In order to access your Django API, requests must be allowed from http://127.0.0.1:4200. For more information on how to enable this feature, refer to Django's CORS documentation. If you're curious about the concept of CORS, you can learn more by visiting this resource.

Answer №2

To enable Cross-Origin Resource Sharing (CORS), as mentioned by @Noremac, you can refer to the documentation for Django.

Begin by installing cors using the command: pip install django-cors-headers.

In your settings.py file, include cors in the INSTALLED_APPS:

INSTALLED_APPS = [
    # Other apps may be listed here...
    'corsheaders',
]

Next, add cors in the MIDDLEWARE section:

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

Note that the corsheaders line should come before any middleware that generates responses, such as CommonMiddleware. Refer to the documentation for more details.
Finally, towards the end of settings.py, you can either allow all origins with CORS_ORIGIN_ALLOW_ALL = True, or specify specific origins like this:

CORS_ORIGIN_WHITELIST = (
    '127.0.0.1:8000'
)

Answer №3

Issue with Google Chrome console

Error encountered in 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

Request blocked due to CORS policy

Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Answer №4

Big thanks, it worked like a charm.

Just to clarify, the proper syntax is:

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

The issue with "ERROR TypeError: Cannot read property 'id' of undefined" arose because the property was located outside the FOR loop.

All sorted now!

Appreciate it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with an Angular HTTP PUT request returning a 404 error for a valid URL on a JSON server!

After trying to implement Angular HTTP put using reactive forms for the first time, I encountered an issue. Whenever I use the code provided, I receive a 404 error. The error specifically points to a server URL that cannot be found (XHR PUT http://localhos ...

Typescript provides the flexibility to construct incomplete or partially valid objects

My attempt to create a partial helper function in Typescript led me to an incorrect version that went unnoticed by Typescript: Typescript version: 5.2.2 type A = { a: number; b: string }; // incorrect const buildPartialBad = (key: keyof A, val: A[keyof A ...

Discovering the versatility of Typescript objects

I want to define a type that follows this rule: If the property container is present, then expect the property a. If the property item is present, then expect the property b. Both container and item cannot exist at the same time. The code I would expect ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

"Update your Chart.js to version 3.7.1 to eliminate the vertical scale displaying values on the left

Is there a way to disable the scale with additional marks from 0 to 45000 as shown in the screenshot? I've attempted various solutions, including updating chartjs to the latest version, but I'm specifically interested in addressing this issue in ...

Leveraging a component as a property of an object in Vue version 3

I'm trying to figure out if there's a way to use a Component as a property in Vue 3. Consider the TypeScript interface example below: import type { Component } from 'vue' interface Route { url: string icon: Component name: ...

Tips for effectively sending prop to a component in React with the help of TypeScript

Hey there, I'm working on a component called FormField which can accept either an icon for create or edit. Currently, I am using this FormField inside another component called SelectWithFormField. Here's how it looks: const FormField = ({create, ...

Angular background image not displayed

After searching extensively, I came across many examples that didn't work for me. I'm not sure what I'm doing wrong and I need assistance! I noticed that I can see the image if I use the <img> tag, but not when I try to set it as a ba ...

Issue with Typescript - Node.js + Ionic mobile app's Angular AoT build has encountered an error

Currently, I am in the process of developing an Android application using Node.js and Ionic framework. The app is designed to display random text and images stored in separate arrays. While testing the app on Chrome, everything works perfectly fine. Upon ...

Ng5 npm is encountering an error stating 'Module './topologicalSort' could not be located.'

I encountered an issue with my Angular 5 app. Whenever I attempt to run it, I receive the following error message after running an npm start. Error: Cannot find module './topologicalSort' I suspect that this issue is related to 'webpac ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": https://i.sstatic.net/TvfEr.png This is how my media.component.ts file is structured: impo ...

Ensure that all content is completely loaded before displaying it using Angular 2

As an Angular developer, I am facing a challenge in my component where I am generating an image through a service HTTP call. Unfortunately, the image generation process takes longer than the site load time, causing the image to not appear immediately on th ...

Is there a way to modify material-ui Input without needing a save button?

Is there a way to automatically save changes in the GraphQL without using a save button? I have implemented code that functions as intended, but with a strange issue. When typing "hello" in the input field, it saves multiple times as individual letters, ra ...

Configuring ordered imports in TSLint

Need help with configuring my TSLint rule ordered-imports. I want the import order to be like this: // React import React from 'react'; import { View } from 'react-native'; // Libs import * as _ from 'lodash'; import * as mo ...

Duplicate routing configuration causing ngOnInit to be triggered twice

Here is my route setup: { path: 'menu/:level/:parent', component: MenuComponent, pathMatch : 'full' }, { path: 'menu', component: MenuComponent, }, I am trying to make it so that if the URL is menu/2/test, it will use ...

Implementing a fixed search bar in Angular for a dropdown selection using mat-select

I'm currently utilizing a mat-select widget from Angular-Material in my application To enhance user experience, I am adding a search bar at the top of the select dropdown for filtering options: <mat-select placeholder="Select a store" ...

Making Angular table cells interactive with clicks

My table consists of multiple rows, and I want to change the color of a cell to red when clicked. However, only one cell should be red at a time. Whenever I click on a new cell, the previously red cell should return to its original color. How can I achieve ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

The issue with Rxjs forkJoin not being triggered within an Angular Route Guard

I developed a user permission service that retrieves permissions from the server for a specific user. Additionally, I constructed a route guard that utilizes this service to validate whether the user possesses all the permissions specified in the route. To ...

Preview of Azure AD Consent Scopes and Access Token Version Error in Msal Angular

Currently in the process of updating my web application with the new MSAL library, @azure/msal-angular, from previously using the old ADAL library. The frontend of the web app is built with Angular 5 and communicates with a backend ASP.NET Core Web API. ...