Skvupp
Skvupp

Reputation: 175

Error: 422 (Unprocessable Entity). Angular4

I am trying to post data from Angular4 on localhost:4200 to an API on localhost:8000. I works fine with Postman, but not with Angular. Then I get:

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)

This is the service that posts to api:

@Injectable()
export class ApiService {
    constructor(private http: Http) { }
    login(username: string, password: string): Observable<Response>{
        const url = 'http://localhost:8000/login';
        const json = JSON.stringify({username: username, password: password});
        const headers: Headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=UTF-8');
        return this.http.post(url, json, headers )
            .map(res => res.json());
    }
}

This is the code that runs the method

   logIn(user: string, password: string){
      this.apiService.login(user, password).subscribe(
          data => console.log(data),
          error => console.log(error)
      );
    }

Upvotes: 4

Views: 12364

Answers (3)

Tch&#234;
Tch&#234;

Reputation: 11

Take a look into you backend, in delete fuction, it's common happens when you call DELETE method and try to processos some data from body, but DELETE don't have a body, take a look if u don't have in your delete something like:

err := c.BodyParser(&user)

here BodyParser is the problem, u can't do it cuz you dont have a body

Upvotes: 0

Sandesh Kumar
Sandesh Kumar

Reputation: 161

I am also getting same issue while using the 'angular-in-memory-web-api'. The problem was while creating the InMemoryDbService i have not added the primary key like id. after added the id in createDb instance it's working fine for me.



import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';

@Injectable({
  providedIn: 'root'
})
export class DataService implements InMemoryDbService {

  constructor() { }
  createDb() {

    let users = [
      {**id: 1**, username: "Sandy", firstname: "Sandesh", lastname: "K", password: 
        "XXXX", description: "Hi, Going to save data", gender: "Male" }
    ];
    return { users };

  }
}

Upvotes: 2

Amr Abdalrahman Ahmed
Amr Abdalrahman Ahmed

Reputation: 1020

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.

For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Upvotes: 1

Related Questions