Angular 6 HTTP客户端发布-错误的请求

时间:2018-08-18 20:11:00

标签: angular

我有以下问题。 我有一个使用API​​的服务器,我将请求发送到注册端点,但是作为响应,我收到了400 Bad Request错误,指出必须填写名称,姓氏,电子邮件等。问题在于它们已被填充。我不再想念想法了。我的代码:

import {Component} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
    title = 'Brak tytułu';

    constructor(private http: HttpClient) {
    }

    registerUser() {
        const config = {headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')};
        const user: User = {
            name: 'Pawel',
            surname: 'Tester',
            email: 'tester@wp.pl',
            password: 'loremipsum12',
            password_confirm: 'loremipsum12',
            event_id: 1,
        };

        this.http.post('https://myapiserver', user, config).subscribe((res) => {
                console.log(res);
                console.log(user);
            },
            error => {
                console.log(error);
                console.log(user);
            });
    }
}

interface User {
    name: string;
    surname: string;
    email: string;
    password: string;
    password_confirm: string;
    event_id: number;
}

此代码可以正常工作,但他是angularJS

    // User create
$scope.createUser = function()
{
    var create_req = $rootScope.reqDefaults;
        create_req.method = 'POST';
        create_req.url = $rootScope.api+'/admin/user';
        create_req.data = $httpParamSerializerJQLike($scope.current);
        create_req.transformRequest = angular.identity;

    // Users list
    $http(create_req)
        .then(function(response){
            $location.path('/users');
            $.notify({
                title: '<strong>Użytkownik utworzony.</strong>',
                message: $scope.current.name+' '+$scope.current.surname+' (ID: '+response.data.id+')'
            },{
                type: 'success'
            });
            return true;
        }, function(response){
            $rootScope.rspError(response.data);
            return false;
        });
};

如果我从Postman向注册端点发送请求,一切正常,则我的用户正确注册了:(我将内容类型设置为application / x-www-form-urlencoded。

4 个答案:

答案 0 :(得分:1)

这对我有用

const config = new HttpHeaders().set('Content-Type', 'application/json')
                                .set('Accept', 'application/json')

this.http.post('https://myapiserver', JSON.stringify(user), 
               { headers: config }).subscrib.....

希望这会有所帮助

编辑:使用新的HttpClientModule

const formData = new FormData();

// append your data
formData.append('myKey1', 'some value 1');
formData.append('myKey1', 'some value 2');
formData.append('myKey3', true);

this.httpClient.post('https://myapiserver', formData);

请勿设置Content-Type标头,Angular会为您解决! 来源:How to force Angular2 to POST using x-www-form-urlencoded

答案 1 :(得分:1)

HttpClient中的Angular实际上很聪明,可以确定您的请求应具有哪种类型的内容。通过查看this行的源代码

if (this.body instanceof HttpParams) {
  return 'application/x-www-form-urlencoded;charset=UTF-8';
}

如果将正文设置为HttpParams,则会看到它将为您设置所需的标头。因此,解决您的问题的方法应该是:

const body = new HttpParams()
  .set('name', 'foo')
  .set('surname', 'bar')

this.http.post('https://myapiserver', body).subscribe(...);

答案 2 :(得分:0)

不设置内容标头,默认情况下会将其设置为JSON,或者将其设置为JSON,例如:application/json

但是,如果您的API需要使用表单编码的有效内容,那么您应该像保留标题一样保留标头,但可以修改请求以发送表单编码的数据,如下所示:

  const body = new HttpParams()
    .set('name', 'Pawel')
    .set('surname', 'Tester');

  this.http.post('https://myapiserver',
    body.toString(),
    config
  );

答案 3 :(得分:0)

我在这里看到的两个主要问题: HttpHeaders 缺少授权:

const config = {headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
HttpHeaders().set('Authorization': 'Basic ' + credentials);
HttpHeaders().set('Accept':'*/*')
};

凭证可以在哪里:const credentials = btoa("angularUser"+":"+"password"); 必须在要验证的后端的 CORS 中定义。

另外一个是body,应该定义如下:

let user = new URLSearchParams();

user.set('param1', 'value1');
user.set('param2', 'value2');

...

如果不起作用,请尝试将 Content-type from 'application/x-www-form-urlencoded' 更改为 'application/json'。 这至少对我有用。

相关问题