Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 HTTP Client Post - Bad request

Tags:

angular

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. 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: '[email protected]',
            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

    // 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.

like image 431
PawelC Avatar asked Apr 12 '26 12:04

PawelC


2 Answers

The HttpClient from Angular is actually very smart in figuring out what type of content should your request have. 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. 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(...);
like image 60
Claudiu Hojda Avatar answered Apr 22 '26 22:04

Claudiu Hojda


Don't set the content headers, which will set them to JSON by default , or set them for JSON like that: 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:

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

  this.http.post('https://myapiserver',
    body.toString(),
    config
  );
like image 28
abdullahkady Avatar answered Apr 22 '26 20:04

abdullahkady



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!