首页 > 解决方案 > 带有 x-www-form-urlencoded 数据的 Angular 6 http 发布请求

问题描述

我一直在尝试向我支持的 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)
                    );
    }
}

标签: angularionic-frameworkhttpclient

解决方案


我试图从端点获取一个 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": ""
    }
  }
}

推荐阅读