【问题标题】:Post Error From Angular to Net Core HTTP 404从 Angular 到 Net Core HTTP 404 发布错误
【发布时间】:2021-12-22 08:39:29
【问题描述】:

我正在创建一个全栈 Web 软件,我正在使用 Angular、Net Core 和 Mssql...我的 Web api 已经准备好,如果我使用 Postman,没有任何问题。我可以在网页上的 Bootstrap 表中列出所有产品。但是,如果从 Angular(角度形式)发送信息,则会出错。 “无法将 JSON 值转换为 System.Int32” 看起来像类型转换错误。我将验证规则从categoryId: ["", Validators.required] 更改为categoryId: [parseInt(""), Validators.required]categoryId: [0, Validators.required] 我的模型变量类型是数字。我不明白。提前谢谢...

我在 Github 的整个项目:https://github.com/SuperSayiyajin/FullStack_Workshop/tree/main/Northwind_Final

这是我的 Net Core WebApi 控制器方法:

[HttpPost("add")]
public IActionResult Add(Product p)
{
    var result = _productService.Add(p);
    if (result.Success)
    {
        return Ok(result);
    }
    return BadRequest(result);
}

这是我的产品添加模块:

import { ToastrService } from 'ngx-toastr';
import { ProductService } from './../../services/product.service';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators } from "@angular/forms";

@Component({
    selector: 'app-product-add',
    templateUrl: './product-add.component.html',
    styleUrls: ['./product-add.component.css']
})
export class ProductAddComponent implements OnInit {
    addProductForm: FormGroup;
    constructor(private formBuilder: FormBuilder,
        private productService: ProductService,
        private toastrService: ToastrService) { }

    ngOnInit(): void {
        this.createAddProductForm();
    }

    createAddProductForm() {
        this.addProductForm = this.formBuilder.group({
            productName: ["", Validators.required],
            categoryId: ["", Validators.required],
            unitsInStock: ["", Validators.required],
            unitPrice: ["", Validators.required],
        });
    }

    addProduct() {
        if (this.addProductForm.valid) {
            let product = Object.assign({}, this.addProductForm.value);
            this.productService.addProduct(product).subscribe(response => {
                console.log(response);
                this.toastrService.success(response.message, "Completed")
            }, responseError => {
                console.log(responseError.error);
                this.toastrService.error(responseError.error);
            });
        } else {
            this.toastrService.error("Product is not valid", "Error");
        }

        //console.log(product);
    }
}

这是我的产品服务。

import { ResponseModel } from './../Models/responseModel';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ListResponseModel } from '../Models/listResponseModel';
import { Product } from '../Models/product';

@Injectable({
    providedIn: 'root',
})
export class ProductService {
    apiURL = 'https://localhost:44324/api/';

    constructor(private httpClient: HttpClient) { }

    getProducts(): Observable<ListResponseModel<Product>> {
        let newPath = this.apiURL + 'products/getall';
        return this.httpClient.get<ListResponseModel<Product>>(newPath);
    }

    getProductsByCategoryId(
        categoryId: number
    ): Observable<ListResponseModel<Product>> {
        let newPath =
            this.apiURL + 'products/getallbycategoryid?categoryId=' + categoryId;
        return this.httpClient.get<ListResponseModel<Product>>(newPath);
    }

    addProduct(product: Product): Observable<ResponseModel> {
        return this.httpClient.post<ResponseModel>(this.apiURL + "products/add", product);
    }
}

这是 product-add.html

<div class="content">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="title">Add Product</h5>
            </div>
            <div class="card-body">
                <form [formGroup]="addProductForm">
                    <div class="mb-3">
                        <label class="Labels" for="productName">Product Name</label>
                        <div class="form-group">
                            <input class="col-9" type="text" id="productName" formControlName="productName"
                                class="form-control" placeholder="Product Name" />
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="Labels" for="categoryId">Product Category</label>
                        <div class="form-group">
                            <input type="text" id="categoryId" formControlName="categoryId" class="form-control"
                                placeholder="Category Id" />
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="Labels" for="unitsInStock">Product Stock</label>
                        <div class="form-group">
                            <input type="text" id="unitsInStock" formControlName="unitsInStock" class="form-control"
                                placeholder="Stock" />
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="Labels" for="unitPrice">Product Price</label>
                        <div class="form-group">
                            <input type="text" id="unitPrice" formControlName="unitPrice" class="form-control"
                                placeholder="Price" />
                        </div>
                    </div>
                </form>
            </div>
            <div class="card-footer">
                <button class="btn btn-fill btn-primary" (click)="addProduct()">Add Product</button>
            </div>
        </div>

    </div>

</div>

【问题讨论】:

  • 请从 Network 标签 -> Headers 子标签的底部发布您的 HTTP 请求的有效负载,以及 .net core 中 Product 类的定义
  • 感谢您的快速回答。我将它们作为图片 4-5-6 添加到第一条消息中。看起来像角度将它们作为字符串发送。
  • 您可以尝试点击Request Payload上的“查看源代码”,将JSON复制粘贴到Postman中,看看是否会出现同样的错误?
  • 如果粘贴的 JSON 不起作用,罪魁祸首可能是从前端发布的字符串类型。您可以尝试通过将相应输入字段的 type='text' 更改为 type='number' 来解决此问题。您也可以在收集表单值之后发送 API 之前手动执行 parseInt/parseFloat
  • 是的,它给出了 excat 相同的错误。当角度将整数发送到我的 api 时,整数看起来像字符串

标签: sql-server angular asp.net-core .net-core


【解决方案1】:

感谢冰冷。看来我太累了。输入 type="number" 解决了这个问题。

<div class="form-group">
       <input type="number" id="categoryId" formControlName="categoryId" class="form-control" placeholder="Category Id" />
</div>

【讨论】:

    【解决方案2】:

    产品类中的categoryId 是数字类型,所以是的,您应该使用 categoryId: [0, Validators.required]categoryId: [null, Validators.required]&lt;input type="number"&gt;

    您没有收到编译错误的原因是因为您所有的 Typescript 代码都翻译为 JavaScript,而在 JS 中我们没有像 typescript 中那样的类型检查。 请注意,this.form.value 的类型是 any,这就是 typescript 也没有检测到它的原因。

    【讨论】:

    • 他们没有工作... categoryId: [0, Validators.required], categoryId: ["", Validators.required], categoryId: [parsenInt(""), Validators.required], categoryId : [null, Validators.required],
    • 所以问题出在输入类型上,我编辑了我的答案只是为了得到完全正确的答案。
    猜你喜欢
    • 2018-06-04
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2019-06-08
    相关资源
    最近更新 更多