我想使用Axios从VueJS中的表单发送数据。 但是我不知道在发送对象之前怎么写
查看:
methods: {
createPost() {
let autorData = {
nom: this.nom,
}
let postData = {
titre: this.titre,
auteur: autorData,
contenu: this.contenu,
};
this.__submitToServer(postData);
},
__submitToServer(data) {
axios.post(`${server.baseURL}/post/create`, data).then(data => {
router.push({ name: "home" });
});
}
}
控制器:
import { Controller, Get, Res, HttpStatus, Param, Post, Body, NotFoundException } from '@nestjs/common';
import { PostService } from './post.service';
import { CreatePostDTO } from './dto/create-post.dto';
@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) { }
...
@Post('/create')
async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) {
const post = await this.postService.addPost(createPostDTO);
return res.status(HttpStatus.OK).json({
message: "Post has been created successfully",
post
})
}
}
模型:CreatePostDTO
import { User } from 'src/user/interfaces/user.interface';
export class CreatePostDTO {
readonly titre: string;
readonly auteur: User;
readonly contenu: string;
}
模型:界面用户
export interface User extends Document {
readonly nom: string;
}
如何使“作者”数据是我的“帖子”的子对象?
编辑
服务器错误
ValidationError: Post validation failed: auteur: Cast to ObjectID failed for value "{}" at path "autor"
...
at PostService.addPost (C:\Users\me\Desktop\Try\VueJS_NestJS_MongoDB\diy\customer-list-app-backend\src\post\post.s at C:\Users\yann.surzur\Desktop\Try\VueJS_NestJS_MongoDB\diy\customer-list-app-backend\src\post\post.controller.ts:19:71
message: 'Cast to ObjectID failed for value "{}" at path "autor"', name: 'CastError',
stringValue: '"{}"',
kind: 'ObjectID',
value: {},
path: 'autor',
reason: [MongooseError] } },
_message: 'Post validation failed',
name: 'ValidationError'
存在问题:“在路径“ autor”上对值“ {}”的对象ID投射失败”。 这就是为什么我认为在发送数据之前写数据时会犯错的原因。