Angular 6 HTTP Client Post - 错误的请求 [英] Angular 6 HTTP Client Post - Bad request

查看:35
本文介绍了Angular 6 HTTP Client Post - 错误的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.我有一个 API 所在的服务器,我将请求发送到注册端点,但作为响应,我收到 400 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. 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;
}

这段代码工作正常,但他是angularJS

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

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

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.

推荐答案

Angular 中的 HttpClient 实际上非常聪明地确定您的请求应该包含什么类型的内容.通过查看 this 上的源代码 线

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

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

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(...);

这篇关于Angular 6 HTTP Client Post - 错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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