问题描述
我第一次尝试使用响应式表单来应用 Angular HTTP put。我的问题是当我应用以下代码时,我收到 404 错误。该错误指示未找到服务器 URL (XHR PUT http://localhost:3000/Feedback)。当我单独使用 URL 时,它会正常带来数据,来自 JSON 服务器的消息是 200 (GET /Feedback 200 28.207 ms - 200)。这意味着 URL 没有问题!!!但是,在 HTTP put 的情况下还是得到 404
JSON 服务器结构(我需要放入“反馈”:[])
{
"dishes": [ ...
],"promotions": [ ...
],"leaders": [ ...
],"Feedback": [
{
"firstname": "Ali","lastname": "Sleam","telnum": "123123123","email": "Ali@gmail.com","agree": false,"contacttype": "None","message": "This is my message"
}
]
}
Feedback.service.ts
...
export class FeedbackService {
constructor(private http: HttpClient,private processHTTPMsgService: ProcessHTTPMsgService) { }
submitFeedback(FeedBack: Feedback): Observable<Feedback> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.put<Feedback>('http://localhost:3000/Feedback',FeedBack,httpOptions);
}
}
component.ts
...
FeedbackForm: FormGroup;
Feedback: Feedback;
contactType = ContactType;
...
constructor(private fb: FormBuilder,private FeedbackService: FeedbackService) {
this.createForm();
}
...
createForm() {
this.FeedbackForm = this.fb.group({
firstname: ['',[Validators.required,Validators.minLength(2),Validators.maxLength(25)] ],lastname: ['',telnum: ['',Validators.pattern] ],email: ['',Validators.email] ],agree: false,contacttype: 'None',message: ''
});
}
...
onSubmit() {
this.Feedback = this.FeedbackForm.value;
this.FeedbackService.submitFeedback(this.Feedback) // <--- add to the server (put)
.subscribe(Feedback => { this.Feedback = Feedback; },errmess => { this.Feedback = null; this.errMess = <any>errmess; });
}
component.html
<form novalidate [formGroup]="FeedbackForm" #fform="ngForm" (ngSubmit)="onSubmit()">
...
<button type="submit" mat-button class="background-primary text-floral-white">Submit</button>
</form>
更新——反馈类
export class Feedback {
firstname: string;
lastname: string;
telnum: number;
email: string;
agree: boolean;
contacttype: string;
message: string;
};
export const ContactType = ['None','Tel','Email'];
解决方法
由于 URL 作为 GET 请求工作,而不是使用 http.put
,请尝试使用 http.get
这与 Angular 无关。您正在使用 PUT Request
访问在服务器中公开为 GET Request
的 URL。
由于服务器不知道 PUT 请求,它发送 404。
我终于找到了解决这个问题的方法,基于答案Here
JSON 服务器需要一个 id,而我的类没有包含一个 id。为 id 分配一个值并不重要,但必须至少将其包含在类中,如下所示。
export class Feedback {
id: number;
firstname: string;
...
};