首页 文章

使用x-www-form-urlencoded数据的Angular 6 http post请求

提问于
浏览
0

我一直试图向我支持的API发布帖子请求以发布一些数据 . 我已经使用邮递员尝试了这个API,它工作正常,数据正确返回 . 但是,当我尝试从我的离子角应用程序执行相同操作时,它根本不起作用 . 我已尝试过网上提供的大部分方法,但无济于事 . 我正在使用Angular v6.0.8和Ionic framework v4.0.1构建此应用程序 . API期望请求正文中的application / x-www-form-urlencoded数据(包括用户名,密码和grant_type) . 我尝试过使用遗留的http和新的httpClient模块,但没有运气 . 到目前为止,我已尝试使用URLSearchParams / JSONObject / HttpParams来创建请求的主体 . 对于 Headers ,我使用HttpHeaders()将application / x-www-form-urlencoded作为Content-Type发送 . 这些方法都不起作用 .

有人能帮我一下吗?

PFB到目前为止我尝试过的方法之一 .

谢谢,Atul

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

4 回答

  • 4

    你不需要 JSON.stringify(formData) 只需传递 formData 作为 http.post 方法的第二个参数 .

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

    和_2703083这样 .

    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

    我试图从 endpoints 获取一个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
    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)
                        );
        }
    }
    
  • 0

    尝试添加:

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

    然后发帖子:

    this.http.post(url, body, options).....
    

相关问题