【问题标题】:I have a todo app made by angular and the system sends some error我有一个由 Angular 制作的待办事项应用程序,系统发送一些错误
【发布时间】:2020-03-24 22:54:38
【问题描述】:

当我要发帖时,系统会将 405 错误消息发送回控制台。我不知道我是怎么做到的,我该如何解决。

或者如果我按下完成按钮,那么控制台将返回 500 错误消息。

这是 HTML

<input
  (keyup.enter)="createPost(name)" #name
  type="text" class="form-control">
<ul class="list-group">
  <li
  *ngFor="let post of posts"
  [ngClass]="post.completed?'list-group-item list-group-item-success':'list-group-item'">
  <button
    (click)="updatePost(post)"
    class="btn btn-outline-success btn-sm" id="button">
    {{ post.completed ? 'Done' : 'Not ready' }}
  </button>
  <button
    (click)="deletePost(post)"
    class="btn btn-outline-danger ml-2 btn-sm">
    Delete
  </button>
  {{ post.name }}
  </li>
</ul>

还有 TypeScript:

export class ToDoAppComponent {
  posts: any;
  private url = 'http://todoapp.test/api';

  constructor(private http: HttpClient) {
    http.get(this.url).subscribe(response => {
      this.posts = response;
    });
  }



  createPost(input: HTMLInputElement) {
    // tslint:disable-next-line: prefer-const
    let post: any = { name: input.value }
    input.value = '';

    this.http.post(this.url, JSON.stringify(post)).subscribe(response => {
      post.id = response.id;
      this.posts.splice(0, 0, post);

    });
  }

  updatePost(post) {
    this.http.put(this.url + '/' + post.id, JSON.stringify({ status: !post.status })).subscribe(response => {
      post.status = !post.status;

    });
  }

  deletePost(post) {
    this.http.delete(this.url + '/' + post.id, ).subscribe(response => {
      let index = this.posts.indexOf(post);
      this.posts.splice(index, 1);
    })
  }
}

附上错误信息和服务器收到的数据

【问题讨论】:

  • 在后端更新 CORS 策略。
  • 您是否尝试过通过邮递员或类似的方式调用 API 端点?除此之外,您似乎有一个cors问题。你打电话给http://todoapp.test/api 表单http://localhost:4200。您可以通过为本地开发服务器 see here 创建代理或在后端更新 CORS 策略来解决该问题。
  • 是的,我尝试使用 Postman 进行测试,那里的服务器运行良好。 @riorudo
  • 虽然您可以在 Postman 和 Chrome 选项卡中获得响应(使用 todoapp.test/api)。应用调用时会被阻塞。
  • 尝试将 content-type 设置为 application/json..this.http.post&lt;T&gt;( url, JSON.stringify(data), {headers: new HttpHeaders({ 'Content-Type': 'application/json' });

标签: angular typescript http-status-code-405 http-status-code-500


【解决方案1】:

在后端更新 CORS 政策以解决 405 问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-07
    • 2020-09-02
    • 1970-01-01
    • 2012-07-12
    • 2019-07-28
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    相关资源
    最近更新 更多