Ionic 带有x-www-form-url编码数据的Angular 6 http post请求

ghhaqwfi  于 2022-12-08  发布在  Ionic
关注(0)|答案(5)|浏览(210)

我一直在尝试向我支持的API发出发布请求来发布一些数据。我已经用postman尝试过这个API,它工作正常,数据也能正确返回。但是,当我尝试从我的ionic-angular应用程序中做同样的事情时,它根本不起作用。我已经尝试了网络上可用的大多数方法,我正在使用Angular v6.0.8和Ionic framework 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)
                    );
    }
}
2ekbmq32

2ekbmq321#

我试图从一个端点获得一个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错误只是设置一个Angular 代理:

//proxy.conf.json
{
  "/oauth": {
    "target": "URL TO TOKEN ENDPOINT",
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug",
    "pathRewrite": {
      "^/oauth": ""
    }
  }
}
2w2cym1i

2w2cym1i2#

You dont need to JSON.stringify(formData) just pass the formData as the second parameter for the http.post method.
create a instance of FormData . And the append the values that you need to send using the formData.append() .
And the httpHeaders like this.

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)
                    );
0mkxixxg

0mkxixxg3#

请试试这个,它对我很有效:

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

tyky79it4#

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

mefy6pfw5#

下面的一个工作为我在最新的Angular 版本截至目前...

login(username: string, password: string) {
    const params = new HttpParams().set("username", username).set("password",password);

    let myHeaders = {
      headers: new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded'),
        params:params
    }
    this.httpClient
      .post(urlConsts.hostport + urlConsts.login, {}, myHeaders)
      .subscribe(
        (res) => {
          console.log('RES::', res);
        },
        (error: HttpErrorResponse) => {
          console.log('ERR::', error);
          if (error.status == 403) {
            this.snackbarShow('Invalid Credentials', 'Ok');
          }
        }
      );
  }

相关问题