我有以下问题。我有一个使用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: '[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;
}
这段代码可以正常工作,但是他是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。
实际上,HttpClient
fromAngular
可以非常聪明地确定您的请求应包含哪种类型的内容。通过查看此行的源代码
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(...);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句