【问题标题】:Error: 422 (Unprocessable Entity). Angular4错误:422(无法处理的实体)。角4
【发布时间】:2018-03-01 04:12:23
【问题描述】:

我正在尝试将数据从 localhost:4200 上的 Angular4 发布到 localhost:8000 上的 API。我在 Postman 上工作得很好,但在 Angular 上却不行。然后我得到:

加载资源失败:服务器响应状态为 422 (Unprocessable Entity)

这是发布到 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());
    }
}

这是运行该方法的代码

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

【问题讨论】:

  • 为什么要在构造函数中定义方法?
  • 我没有。我定义了对象 http。这是一种有角度的做法。
  • 对不起,我没有看到 { }
  • 你找到解决方案了吗@Skvupp
  • 是的,这是使用 Lumen 框架的服务器问题。 Angular 代码是正确的。

标签: angular http-post http-status-code-422


【解决方案1】:

422 (Unprocessable Entity) 状态码表示服务器 理解请求实体的内容类型(因此 415(不支持的媒体类型)状态码不合适),并且 请求实体的语法是正确的(因此是 400 (Bad Request) 状态码不合适)但无法处理包含的 说明。

例如,如果 XML 请求正文包含格式正确(即语法正确)但语义错误的 XML 指令,则可能会发生这种错误情况。

【讨论】:

    【解决方案2】:

    我在使用“angular-in-memory-web-api”时也遇到了同样的问题。问题是在创建 InMemoryDbService 时我没有添加像 id 这样的主键。在 createDb 实例中添加 id 后,它对我来说工作正常。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      相关资源
      最近更新 更多