Angular 6 http发布请求以及x-www-form-urlencoded数据 [英] Angular 6 http post request with x-www-form-urlencoded data

查看:439
本文介绍了Angular 6 http发布请求以及x-www-form-urlencoded数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试向支持的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.这些方法都不起作用.

I have been trying to make a post request to my backed API to post some data. I have tried this API using postman and it works fine and the data is returned properly. However, when I try to do the same from my ionic-angular app, it doesn't work at all. I have tried most of the methods available on the web, but to no avail. I am building this app with Angular v6.0.8 and Ionic framework v4.0.1. The API expects application/x-www-form-urlencoded data in the request body (includes username, password and grant_type). I have tried using both legacy http and the new httpClient module but no luck. So far, I have tried using URLSearchParams/JSONObject/HttpParams for creating the body of the request. For headers I used HttpHeaders() to send application/x-www-form-urlencoded as Content-Type. None of these methods work.

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

Can anyone help me here?

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

PFB one of the methods I've tried so far.

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

推荐答案

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

I was trying to just get an oauth token from an endpoint, and what I can say it is really hard to find a working answer.

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

Below is how I made it work in Angular 7 but this will also work in 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错误,只需设置一个角度代理:

If you get cors errors just set up a angular proxy:

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

这篇关于Angular 6 http发布请求以及x-www-form-urlencoded数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆