[英]axios post request is sending a request header of Content-Type: multipart/form-data resulting in undefined req.body
[英]req.body returning undefined when sending data as form-data
When I'm sending data in my Node.js application as raw JSON/x-www-form-urlencoded from postman it's getting passed but when sending the data as form-data from postman or from my angular frontend, req.body
is coming as undefined . 我在我的 Node.js 应用程序的 index.js 上使用body-parser
。
app.post(`${baseUrl}/post-news`, (req, res) => {
CategoryModel.findOne(
{ categoryId: req.body.category },
(err, result) => {
if (err) {
console.log("Error at finding category ::", err);
res.send(err);
}
if (result) {
let newArticle = new ArticleModel({
categoryName: result.categoryName,
categoryId: result.categoryId,
imagePath: req.file && req.file.path
});
newArticle.save((err, result) => {
if (err) {
console.log("Error at saving new news ::", err);
res.send(err);
} else {
console.log("Successfully saved new news");
res.send(result);
}
});
} else {
console.log("No category found for ::", req.body.category);
res.send("No category found");
}
}
);
});
index.js
app.use(bodyParser.urlencoded({ limit: "10mb", extended: true }));
app.use(bodyParser.json({ limit: "10mb" }));
HTML:
<form fxLayout="row wrap" [formGroup]="createNewsForm" (ngSubmit)="createNews()"
enctype="multipart/form-data">
<div fxFlex="100" fxFlex.gt-sm="100" class="px-1" ngClass.sm="mt-1" ngClass.xs="mt-1">
<label>Title</label>
<mat-form-field class="w-100 form-group">
<input type="text" matInput placeholder="Article title (required)"
formControlName="articleTitle" name="articleTitle" required>
<mat-error *ngIf="articleTitle?.invalid">Please enter a valid Title</mat-error>
</mat-form-field>
</div>
<div fxFlex="100" fxFlex.gt-sm="100" class="px-1" ngClass.sm="mt-1" ngClass.xs="mt-1">
<label>Category</label>
<mat-form-field class="w-100 form-group">
<select matNativeControl formControlName="articleCategory" name="articleCategory"
color="accent">
<option *ngFor="let category of categories" [value]="category.categoryId">
{{category.categorySlug}}</option>
</select>
</mat-form-field>
</div>
<div class="button-wrap" fxFlex="100" fxFlex.gt-sm="100" class="px-1" ngClass.sm="mt-1"
ngClass.xs="mt-1">
<button class="btn-project" mat-raised-button color="accent" type="submit">Post News</button>
</div>
</form>
组件.ts
createNewsForm: FormGroup;
ngOnInIt() {
this.createNewsForm = this.formBuilder.group({
articleTitle: ['', Validators.required],
articleCategory: ['', Validators.required],
imagePath: ['', Validators.required]
})
}
public createNews: any = () => {
const formData = new FormData();
formData.append('imagePath', this.createNewsForm.get('imagePath').value);
formData.append('title', this.createNewsForm.get('articleTitle').value);
formData.append('category', this.createNewsForm.get('articleCategory').value);
this.appService.createNews(formData).subscribe(
data => {
console.log(data)
},
error => {
console.log(error);
})
}
应用服务.ts
import { HttpClient } from '@angular/common/http';
public createNews = (formData) => {
let myResponse = this.http.post(this.baseUrl + '/api/v1/post-news', formData);
return myResponse;
}
您需要一个适当的解析器来处理多部分/表单数据(这是在邮递员中选择“表单数据”后将设置的内容类型),内置的 bodyParsers(urlencoded/json) 不处理它。 您可以使用的一种流行的 package 是multer 。
它们提供了一个upload
中间件,您可以将其插入您的路由处理程序,例如:
const upload = multer({ dest: 'uploads/' })
app.post(`${baseUrl}/post-news`, upload.single('file'), (req, res) => {
// req.file will now hold the uploaded file
// req.body will hold the text fields of the form
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.