Angular 6 http发布请求以及x-www-form-urlencoded数据

时间:2018-07-31 04:38:37

标签: angular ionic-framework httpclient

我一直在尝试向支持的API发送发布请求以发布一些数据。我已经尝试使用邮递员使用此API,并且可以正常工作,并且可以正确返回数据。但是,当我尝试通过离子角度应用程序执行相同操作时,它根本无法工作。我尝试了网络上可用的大多数方法,但是都没有成功。 我正在使用Angular v6.0.8和Ionic框架v4.0.1构建此应用程序。该API要求请求正文中包含application / x-www-form-urlencoded数据(包括用户名,密码和grant_type)。我尝试使用旧版http和新的httpClient模块,但没有运气。到目前为止,我已经尝试使用URLSearchParams / JSONObject / HttpParams创建请求的正文。对于标头,我使用HttpHeaders()发送以Content-Type编码的application / x-www-form-urlencode。这些方法都不起作用。

有人可以在这里帮助我吗?

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)
                    );
    }
}

5 个答案:

答案 0 :(得分:4)

您不需要JSON.stringify(formData),只需将formData作为http.post方法的第二个参数即可。

创建FormData的实例。然后附加您需要使用formData.append()发送的值。

还有httpHeaders这样的

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/x-www-form-urlencoded'
  })};

const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
formData.append('grant_type', 'password');

this.http.post(apiUrl,formData,httpOptions)
                    .subscribe(
                        (res) => {
                            console.log(res);
                        },
                        err => console.log(err)
                    );

答案 1 :(得分:2)

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

答案 2 :(得分:0)

The key "grant_type" may not be taking due to underscore. Try removing underscore.

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 = {
       'username': 'abc',
       'password': 'abc@123',
       'granttype': 'abc@123'
       }

        this.http.post(apiUrl,formData)
                    .subscribe(
                        (res) => {
                            console.log(res);
                        },
                        err => console.log(err)
                    );
    }
}

答案 3 :(得分:0)

请尝试此方法对我有用:

login(user: string, password: string) {
    const params = new HttpParams({
        fromObject: {
            // grant_type: 'password',
            email: 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(this.apiUrl+"/ecs/JSON/login.php", 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)
             );

答案 4 :(得分:-1)

尝试添加此内容:

key: YSIdjo
captcha: 03AEMEkElJT5P54gy_EmbbEG17u6Mb0hZaKOtMOFXVVfkhi34eWN6V_e8Hp-_HDU6_o3_Mbo9rRHjf6D0llY5XClxso3VATocPPtYv0BHNlcfUj2DqCg9LDGQtfuXtCARw5yVEBQU0pZ2BY8KNc2xhfxokVaT9jvIZOEVr1301xiwws7eUdxP5uvynGiQlcXi2VAVVtpsBr-[JUST-CONSORE]-b3gVqVpIA
nonce: 0284c09f44

然后发布:

var headers = new HttpHeaders()
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });