以下是我与postman 的Post API工作问候

router.post(`/`,  uploadOptions.single('image'), async (req, res) =>{
    const category = await Category.findById(req.body.category);
    if(!category) return res.status(400).send('Invalid Category')

    const file = req.file;
    if(!file) return res.status(400).send('No image in the request')
    const fileName = req.file.filename
    const basePath = `${req.protocol}://${req.get('host')}/public/uploads/`;

    let product = new Product({
        name: req.body.name,
        description: req.body.description,
        richDescription: req.body.richDescription,
        image: `${basePath}${fileName}`,
        brand: req.body.brand,
        price: req.body.price,
        category: req.body.category,
        countInStock: req.body.countInStock,
        rating: req.body.rating,
        numReviews: req.body.numReviews,
        isFeatured: req.body.isFeatured,
    })

    product = await product.save();
    
    if(!product)
    return res.status(500).send('The product cannont be created')
    res.send(product);
})

这是我的表格

<div class="container">
  <div class="fadein">
    <h2 class="page-header">add new product </h2>
    <!-- <div class="alert alert-danger" *ngIf="" role="alert"></div> -->
    <form #addProductForm="ngForm" (ngSubmit)="SubmitData(addProductForm)">
      <div class="form-group">
          <label for="name">Name
              <sup class="red">*</sup>
          </label>
          <input required name="name" id="name" #name="ngModel" ngModel type="text" class="form-control">
      </div>
        <div class="form-group">
            <label for="description">description
                <sup class="red">*</sup>
            </label>
            <input required name="description" id="description" #description="ngModel" ngModel type="text" class="form-control">
        </div>
        <div class="form-group">
          <label for="richDescription">richDescription
              <sup class="red">*</sup>
          </label>
          <input required name="richDescription" id="richDescription" #richDescription="ngModel" ngModel type="text" class="form-control">
      </div>
      <div class="form-group">
        <label for="brand">brand
            <sup class="red">*</sup>
        </label>
        <input required name="brand" id="brand" #brand="ngModel" ngModel type="text" class="form-control">
    </div>
    <div class="form-group">
      <label for="price">price
          <sup class="red">*</sup>
      </label>
      <input required name="price" id="price" #price="ngModel" ngModel type="number" class="form-control">
  </div>
  <div class="form-group">
    <label for="category">category
        <sup class="red">*</sup>
    </label>
    <input required name="category" id="category" #category="ngModel" ngModel type="text" class="form-control">
</div>
<div class="form-group">
  <label for="countInStock">countInStock
      <sup class="red">*</sup>
  </label>
  <input required name="countInStock" id="countInStock" #countInStock="ngModel" ngModel type="number" class="form-control">
</div>
<div class="form-group">
  <label for="image">image
      <sup class="red">*</sup>
  </label>
  <input required  type="file" name="file" #file="ngModel" [ngModel]  accept="image/*">

</div>
        <br>
        <input type="submit" class="btn btn-primary" value="Add Product" [disabled]="!addProductForm.valid">
    </form>
  </div>
</div>

而这来自组件

SubmitData(form: { value:  {
    category: string; name: string; description: string;  brand: string;  richDescription: string;
    price: number; countInStock: number; image: File;
}; }){
    const data = {
      name: form.value.name,
      description: form.value.description,
      richDescription: form.value.richDescription,
      brand: form.value.brand,
      price: form.value.price,
      category: form.value.category,
      countInStock: form.value.countInStock,
      image: form.value.image,
    };


    this.productService.postData(data).subscribe(response => {

      console.log(response);

      });
}

产品服务

import { HttpClient, HttpHeaders , HttpEvent} from "@angular/common/http";
import { Injectable } from '@angular/core';
import { Product } from "../models/Product";
import { map, Observable, switchMap, tap } from "rxjs";

@Injectable({
  providedIn: 'root'
})


export class ProductService {
  // jsonURL = 'assets/data.json';
  warehouseURL = 'http://localhost:5000/v1/products/';



  constructor(private http: HttpClient) { }

  getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(this.warehouseURL)
      .pipe(
        tap(data => console.log('All: ', JSON.stringify(data))),
      );
  }
  getProduct(_id: string): Observable<Product | any> {
    return this.getProducts()
      .pipe(
        map((products: Product[]) => products.find(p => p._id === _id)
        )
      )
  }

  RemoveProduct(_id: string){
    this.http.delete<Product[]>(this.warehouseURL+ _id)
    .subscribe(()=>{
    })
  }
  postData(data: any): Observable<any>{
    return this.http.post(`${this.warehouseURL}`, data)
    .pipe(
      tap(data => console.log('All: ', JSON.stringify(data))),
    );
  }

}

当我try 使用postman 发布时,它工作得很好,但我不能发布来自应用程序本身的数据,并生成错误消息"400 no Image in the Request.".你们能告诉我我的错误是什么吗?非常感谢!

推荐答案

将图像输入标记的name属性更改为image,而不是file,此外,您还需要添加文件侦听器,并在提交时将其包括在表单中:

<input type="file" name="image" #image="ngModel" [ngModel] accept="image/*" (change)="onFileChange($event)">

此外,你需要准备form-data个,然后发送它,而不是一个对象.

// file holder
image?: File | any;

// file listener
onFileChange(event: any) {
if (event.target.files.length > 0) {
  const file = event.target.files[0];
  this.image = file
}
}

SubmitData中构造形式:

   const data = new FormData();

    data.append('name', form.value.name);
    data.append('description', form.value.description);
    data.append('richDescription', form.value.richDescription);
    data.append('brand', form.value.brand);
    data.append('price', form.value.price);
    data.append('category', form.value.category);
    data.append('countInStock', form.value.countInStock);
    data.append('image', this.image);

Node.js相关问答推荐

需要关于基于角色授权的设计建议

postgresql层与应用层的序列化

无法从ejs Web应用程序中的正文中提取数据

如何使用多个OR参数从多个集合聚合

Mongoose-如何从父文档填充到子文档

EJS ForEach循环标记

在Docker容器404页面中找不到服务器(提供静态reactjs文件)

Sequelize、postgres和posgis:在n°;公里

Playwright - 无法在 img 标签中使用 file:// 访问本地文件

Next.js 路由不起作用 - 页面未正确加载

未授权使用联合身份未授权用户角色从 Amplify graphQL 访问类型 Y 上的 X

我如何在 Raku 的供应中注册不同的事件?

使用 Nodejs 获取 Firebase 云消息传递历史记录

node-gyp: "..\src\binding.cc: 没有这样的文件或目录"

如何让 vscode 假设一个 node.js 上下文,以便它不假设 `fetch` 存在?

无法通过谷歌Electron 表格 api( node js)中的服务帐户访问写入

无法更新MongoDB中的文档:";伯森场';writeConcern.w';是错误的类型';数组'&引用;

无法获取 CSS 文件

如何在 node 中转义 shell 命令的字符串?

Selenium WebDriver 等到元素显示