带有 x-www-form-urlencoded 数据的 Angular 6 http post 请求

2023-11-26

我一直在尝试向我支持的 API 发出发布请求以发布一些数据。我已经使用邮递员尝试过这个 API,它工作正常并且数据正确返回。然而,当我尝试从我的 ionic-Angular 应用程序中执行相同操作时,它根本不起作用。我已经尝试了网上大部分可用的方法,但没有效果。 我正在使用 Angular v6.0.8 和 Ionic 框架 v4.0.1 构建这个应用程序。 API 期望请求正文中包含 application/x-www-form-urlencoded 数据(包括用户名、密码和 grant_type)。我尝试过使用旧版 http 和新的 httpClient 模块,但没有成功。到目前为止,我已尝试使用 URLSearchParams/JSONObject/HttpParams 来创建请求正文。对于标头,我使用 HttpHeaders() 将 application/x-www-form-urlencoded 作为 Content-Type 发送。这些方法都不起作用。

有人能帮我一下吗?

PFB 是我迄今为止尝试过的方法之一。

谢谢, 阿图尔

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) {

    }

    signin(username: string, password: string){
        const formData = new FormData();
        formData.append('username', username);
        formData.append('password', password);
        formData.append('grant_type', 'password');

        this.http.post(apiUrl,formData,
                      {
                          headers: new HttpHeaders({
                            'Content-Type':'application/x-www-form-urlencoded'
                          })
                      }
                    )
                    .subscribe(
                        (res) => {
                            console.log(res);
                        },
                        err => console.log(err)
                    );
    }
}

我试图从端点获取 oauth 令牌,我可以说很难找到有效的答案。

下面是我如何使它在 Angular 7 中工作,但这也适用于 Angular 6

import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';

    login(user: string, password: string) {
        const params = new HttpParams({
          fromObject: {
            grant_type: 'password',
            username: user,
            password: password,
            scope: 'if no scope just delete this line',
          }
        });

        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + btoa('yourClientId' + ':' + 'yourClientSecret')
          })
        };

        this.http.post('/oauth', params, httpOptions)
          .subscribe(
            (res: any) => {
              console.log(res);
              sessionStorage.setItem('access_token', res.access_token);
              sessionStorage.setItem('refresh_token', res.refresh_token);
            },
            err => console.log(err)
          );
      }

如果出现 cors 错误,只需设置一个角度代理:

//proxy.conf.json
{
  "/oauth": {
    "target": "URL TO TOKEN ENDPOINT",
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug",
    "pathRewrite": {
      "^/oauth": ""
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有 x-www-form-urlencoded 数据的 Angular 6 http post 请求 的相关文章

随机推荐