首页 > 解决方案 > 获得成功的帖子()

问题描述

我正在使用 .NET RESTful API 构建一个 Angular2+ 应用程序。在添加我的食谱项目后单击保存后,我会在控制台中收到一条错误消息。似乎没有正确发布()。

添加配方组件 (.html)

<h1>Add a Recipe</h1>
<form class="form-inline">
    <label class="sr-only" for="recipeTitle">Recipes</label>
    <div class="input-group mb-2 mr-sm-2">
      <input type="text" class="form-control" id="recipeTitle" name="recipeTitle" placeholder="Recipe Title" [(ngModel)]="title">
    </div>

    <label class="sr-only" for="count">Ingredient</label>
    <input type="number" class="form-control mb-2 mr-sm-2" id="count" name="count" placeholder="Count" [(ngModel)]="count">

    <label class="sr-only" for="ingredient">Recipes</label>
    <div class="input-group mb-2 mr-sm-2">
      <input type="text" class="form-control" id="ingredient" name="ingredient" placeholder="Ingredient" [(ngModel)]="ingredient">
    </div>
    <p>the count: {{ itemCount }}</p>

    <input type="submit" class="btn btn-primary mb-2" value="Add" (click)="addIngredient()">
  </form>
  <h2>My Ingredients</h2>
    <ul class="list-group">
      <li class="list-group-item" *ngFor="let ingredient of ingredientsArray">
          <span class="badge">{{ ingredient.count }}</span> {{ ingredient.ingredient }}

      </li>
    </ul>

<button type="button" class="btn btn-primary" (click)="saveRecipe()">Save</button>
<button type="button" class="btn btn-danger">Cancel</button>

在后面添加食谱代码

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-add-recipe',
  templateUrl: './add-recipe.component.html',
  styleUrls: ['./add-recipe.component.css']
})
export class AddRecipeComponent implements OnInit {
  itemCount: number;
  count: number;
  ingredient: string = '';
  title: string = '';
  ingredientsArray = [];

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.itemCount = this.ingredientsArray.length;
  }

  addIngredient() {
    this.ingredientsArray.push({ count: this.count, ingredient: this.ingredient });
    this.ingredient = '';
    this.itemCount = this.ingredientsArray.length;
    this.count = null;
  }

  saveRecipe() {
    this.http.post('api/recipes', 
      { title: this.title, ingredients: this.ingredientsArray, itemCount: this.itemCount })
      .subscribe((res: Response) => {
        console.log('should be saved');

      });
  }
}

控制器

[HttpPost]
        public IActionResult Post(string title, List<IngredientsController> ingredients)
        {
            return Ok();
        }

似乎一切都按照应有的方式进行了设置,但是我在控制台中遇到了一个巨大的错误,就像它没有到达一样。错误消息说

消息:“ https://localhost:5001/api/recipes的 Http 失败响应:404 Not Found”

成分.ts

export class Ingredient {
    count: number;
    ingredient: string;
  }

我没有创建页面吗?我是否需要创建某种路由到该 url 的组件?

标签: angularresthttp

解决方案


这里有多个错误点

1) 使用 Http Post,所有参数都必须作为“单个”有效负载。因此,您需要为应用程序中的每种类型的有效负载创建一个专用类,并在客户端代码中构造一个 JSON 以匹配它。例如,在这种情况下,您的课程如下:-

public class Input
{
    public string Title { get; set; }

    /* Your code refers this to IngredientsController list, 
     * However it should be Ingrediends as you don't intend to create a list of actual controllers. 
     * Please check*/
    public List<Ingredients> Ingredients { get; set; }

    public int ItemCount { get; set; }
}

通常,在使用 JSON 时,大小写默认为驼峰式大小写,但如果您愿意,可以通过更改格式化程序将其强制为帕斯卡大小写(只是为了确保您最终得到正确的 JSON 字段名称)

2) 您使用的 Url 是“api/recipies”,但在您的路由中,您可能错过了通过 RouteName 或 RoutePrefix 装饰 url(如果这是基于属性的路由)。如果这是基于约定的路由,请确保您的服务器端控制器名称为“Recipes”,因为路由中的任何差异都会失败。(顺便说一句,你能打电话给控制器吗?

3)不要担心“https”与“http”,这是因为您安装和使用了服务器证书(ng serve --ssl 命令),因此角度 http 模块使用 https 而不是http。

如果这没有帮助,请发布您的控制器代码(只需删除私有和其他方法)以及您遇到的任何其他错误。


推荐阅读