Angular 中的 HTTP POST 请求

问题描述

我正在 Angular 中创建一个 POST 任务,并在代码中进行了以下设置

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',})
};

下面发送'Credentials',格式如下

class Login
    {
        public username: string="";
        public Password: string="";
        public grant_type: string="";
    }

凭据属于登录类型 电话是

return this.http.post(this.baseUrl,JSON.stringify(Credentials),httpOptions);
   

这似乎发送了没有任何内容的 POST。

如果我使用以下方式发送

return this.http.post(this.baseUrl,JSON.stringify(Credentials));
   

它发送信息,但内容类型被发送为“文本/纯文本”,因此我收到 415 错误

我如何正确发送此请求。 我已经使用邮递员检查了 API 是否正确。

谢谢

阿尔佩什

解决方法

您在类上调用 JSON.stringify(),而不是在对象上。 此外,HttpClient 会在内部序列化您在 JSON 中传递的值,因此大多数情况下您不需要使用它。

试试

const credentials: Credentials = {
  username: '',Password: '',grant_type: ''
};
return this.http.post(this.baseUrl,credentials,httpOptions);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...