【发布时间】:2020-07-08 01:26:39
【问题描述】:
我设置了一个简单的 Ionic 5 应用程序和一个 NestJS 后端。现在我想从我的应用程序向我的后端发送一个 POST 请求,但我总是在浏览器控制台中收到以下错误消息:
对象 {headers: {…}, status: 500, statusText: "Internal Server 错误”,网址:“http://localhost:3000/api/users”,确定:假, 名称:“HttpErrorResponse”,消息:“http://localhost:3000/api/users 的 Http 失败响应:500 内部服务器错误”,错误: {…}} home.page.ts: 36: 14
在我的 NestJS 后端中,我收到以下错误消息:
[Nest] 18696 - 03/27/2020, 10:39:04 AM [ExceptionsHandler] 用户 验证失败:密码:路径
password是必需的。,用户名: 路径username为必填项。电子邮件:路径
在浏览器的网络选项卡中,我收到状态代码为 500 的错误(内部服务器错误):
Request URL: http://localhost:3000/api/users
Request method: POST
Remote address: 127.0.0.1: 3000
Status code:
500
Version: HTTP / 1.1
Referrer Policy: no-referrer-when-downgrade
所需的参数也正确发送:
{"email":"test@test.de","username":"testname","password":"testpassword"}
我的 POST 请求的控制器结构如下:
@Controller('/users')
export class UsersController {
constructor(private usersService: UsersService) { }
// POST request containing the data required to create a new user
@Post()
async createUser(@Res() res, @Body() createUserDto: CreateUserDto) {
console.log('body', createUserDto);
const user = await this.usersService.create(createUserDto);
if (!user) throw new InternalServerErrorException('User could not be created!');
return res.status(HttpStatus.OK).json({
message: "User has been created successfully",
user
})
}
...
使用的 DTO 如下所示:
export class CreateUserDto {
readonly email: string;
readonly username: string;
readonly password: string;
}
CORS 在我的 NestJS 后端也被激活。此外,有趣的是 GET 请求(通过 Ionic 以及通过 Postman 或直接输入到浏览器)工作。如果我通过 Postman 发出 POST 请求或直接将它们输入到浏览器中,POST 请求也可以工作。
我在 Ionic 应用程序中以这种方式测试 POST 请求:
ngOnInit() {
this.createAccount(this.createUserDto).subscribe((res) => {
console.log('Request send', res);
}, (err) => {
console.log('Failed', err);
});
}
createAccount(credentials): Observable<any> {
return this.http.post('http://localhost:3000/api/users', JSON.stringify(credentials));
}
当我删除 JSON.stringify(credentials) 并只输入 credentials 而没有 JSON.stringify() 时,请求没有发送也很有趣。
我在这里做错了什么?
【问题讨论】:
-
可能选择了错误的
httpclient.post过载。尝试直接将内容类型指定为 json 并尝试在没有JSON.stringify()的情况下使其工作。它应该在没有JSON.stringify()的情况下工作!this.http.post('http://localhost:3000/api/users', credentials, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) -
不行,还是不行。正文不会传递到我的后端,如果没有 JSON.stringify() 方法,请求将无法工作。 HttpClient 是从“@angular/common/http”导入的。我还添加了你建议的标题..
-
请求怎么不能发送?您是否收到有关预检
OPTIONS请求的 CORS 错误? -
不,我只是收到问题中列出的错误。如果我将正文记录在我的 NestJS 控制器中,例如 console.log('body', createUserDto);它说:body CreateUserDto {}。下面是上面列出的错误。所以我发送到控制器的身体是空的,但在浏览器的网络选项卡中,身体是存在的。另外,如果我将其登录到我的 ionic 应用程序中。
标签: angular typescript ionic-framework rxjs nestjs