简体   繁体   English

Angular 6 HTTP Client Post - 错误的请求

[英]Angular 6 HTTP Client Post - Bad request

I have the following problem.我有以下问题。 I have a server on which the API is, I send the request to the registration endpoint, but in response I get a 400 Bad Request error, stating that the name, surname, email etc must be filled out.我有一个 API 所在的服务器,我将请求发送到注册端点,但作为响应,我收到 400 Bad Request 错误,指出必须填写姓名、姓氏、电子邮件等。 The problem is that they are filled.问题是他们被填满了。 I miss ideas anymore.我不再想念想法了。 My code:我的代码:

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

This code works fine, but he is angularJS这段代码工作正常,但他是 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;
        });
};

If i send request to the register endpoint from Postman, all works fine, my user is register correctly :( I set content type to application/x-www-form-urlencoded.如果我从 Postman 向注册端点发送请求,一切正常,我的用户注册正确:( 我将内容类型设置为 application/x-www-form-urlencoded。

The HttpClient from Angular is actually very smart in figuring out what type of content should your request have. AngularHttpClient在确定您的请求应该包含什么类型的内容方面实际上非常聪明。 By looking into the source code at this line通过查看这一行的源代码

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

you will see that it will set your required header for you if you set the body as HttpParams .如果您将正文设置为HttpParams ,您将看到它将为您设置所需的标头。 So, the solution to your problem should be:因此,您的问题的解决方案应该是:

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

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

Don't set the content headers, which will set them to JSON by default , or set them for JSON like that: application/json不要设置内容标头,默认情况下会将它们设置为 JSON,或者将它们设置为 JSON,如下所示: application/json

If your API however expects form encoded payload, then you should leave the header just like you have it, but modify the request to send form encoded data like this:但是,如果您的 API 需要表单编码的有效负载,那么您应该像拥有​​它一样保留标头,但修改请求以发送表单编码数据,如下所示:

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

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

this works for me这对我有用

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

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

Hope this helps希望这可以帮助

EDIT : using new HttpClientModule编辑:使用新的 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);

Do NOT set Content-Type header, angular will fix this for you!不要设置 Content-Type 标头,angular 会为你解决这个问题! source : How to force Angular2 to POST using x-www-form-urlencoded来源: 如何使用 x-www-form-urlencoded 强制 Angular2 POST

Two main problems I see here: the HttpHeaders is missing the Authorization:我在这里看到的两个主要问题: HttpHeaders 缺少授权:

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

where credentials can be: const credentials = btoa("angularUser"+":"+"password");其中凭证可以是: const credentials = btoa("angularUser"+":"+"password"); must be defined in te CORS of the backend to be validated.必须在要验证的后端的 te CORS 中定义。

Another thing is the body, should be defined as follows:另一件事是body,应该定义如下:

let user = new URLSearchParams();

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

... ...

And if is not working, try to change the Content-type from 'application/x-www-form-urlencoded' to 'application/json' .如果不起作用,请尝试将Content-type from 'application/x-www-form-urlencoded'更改为'application/json' This worked form me at least.这至少对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM