什么导致了这个 Angular 15 和 JSON 服务器应用中的 post 请求失败?

huangapple go评论107阅读模式
英文:

What causes the failure of the post request in this Angular 15 and JSON server app?

问题

  1. 你做错了什么?

    你的代码看起来基本上是正确的,但可能出现了一些常见的问题。首先,请确保你的 Angular 应用程序与 JSON 服务器正常运行,并且没有控制台错误。然后,请检查以下几个可能导致问题的方面:

    • HTTP 请求问题:确保你的 Angular 应用能够正确发送 POST 请求到 JSON 服务器。你可以使用浏览器的开发者工具来检查请求是否成功,以及服务器是否返回了任何错误响应。

    • 数据格式问题:验证你发送的 newEmployee 对象的格式是否与服务器端所需的格式匹配。你可以比较它与服务器端预期的 JSON 数据格式。

    • JSON 服务器配置:检查 JSON 服务器的配置文件是否正确。特别关注你在启动 JSON 服务器时使用的端口和路由路径是否与你的 Angular 应用程序一致。

  2. 如何可靠地解决这个问题?

    为了可靠地解决这个问题,你可以采取以下步骤:

    • 检查服务器端:首先确保 JSON 服务器端正确配置并运行。你可以使用命令行工具(如 curl 或 Postman)测试发送 POST 请求是否能够成功添加数据到服务器。

    • 确认数据传输:确保在发送 POST 请求时,数据正确传输到服务器。你可以在 Angular 应用中添加一些日志来跟踪发送的数据,以确保它们与预期一致。

    • 处理响应:在 Angular 代码中,检查 JSON 服务器返回的响应。你可以使用 Angular 的 HttpClient 来处理服务器的响应,并查看是否有任何错误信息。请确保处理了 HTTP 请求中的错误情况。

    • 查看 JSON 服务器日志:在 JSON 服务器的终端窗口中查看服务器日志,以检查是否有任何错误或警告消息。这可能会提供关于问题的更多信息。

    • 调试代码:使用浏览器的开发者工具或 Angular 的调试功能来检查你的代码。确保 addEmployee 方法被正确调用,并查看是否有任何 JavaScript 错误。

    • 检查数据存储:最后,确保 JSON 服务器正确地存储了数据。你可以检查 JSON 文件是否被更新,或者尝试从服务器获取所有员工以验证是否成功添加。

    通过逐步检查这些步骤,你应该能够找到导致数据没有被添加到 JSON 的根本原因,并采取相应的措施来解决问题。

英文:

I have been working an app with Angular 15.

I use a hand-coded JSON and JSON server to perform CRUD oprations on the "employees" JSON below:

  1. {
  2. "employees": [
  3. {
  4. "empno": "2",
  5. "deptno": "10",
  6. "firstname": "Sandy",
  7. "lastname": "Paton",
  8. "gender": "femele",
  9. "avatar": "sandy.png",
  10. "job": "Manager",
  11. "bio": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam obcaecati veritatis maiore.",
  12. "skills": [
  13. "Management"
  14. ]
  15. },
  16. {
  17. "empno": "4",
  18. "deptno": "30",
  19. "firstname": "Hollie",
  20. "lastname": "Haerr",
  21. "gender": "femele",
  22. "avatar": "hollie.png",
  23. "job": "Programmer",
  24. "bio": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam obcaecati veritatis maiore.",
  25. "skills": [
  26. "HTML5",
  27. "CSS3",
  28. "JavaScript",
  29. "Angular 2+"
  30. ]
  31. },
  32. {
  33. "empno": "6",
  34. "deptno": "30",
  35. "firstname": "Lynde",
  36. "lastname": "Ailyn",
  37. "gender": "femele",
  38. "avatar": "femele.png",
  39. "job": "Programmer",
  40. "bio": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam obcaecati veritatis maiore.",
  41. "skills": [
  42. "HTML5",
  43. "CSS3",
  44. "JavaScript",
  45. "Angular 2+"
  46. ]
  47. }
  48. ]
  49. }

NOTE:

I start the JSON server with npx json-server --watch ./src/app/data/employees.json --id empno.

In employee-form.component.ts I heve:

  1. import { Component } from '@angular/core';
  2. import { Employee } from '../../models/empModel';
  3. import { EmployeeService } from '../../services/employee.service';
  4. import { NgForm } from '@angular/forms';
  5. @Component({
  6. selector: 'app-employee-form',
  7. templateUrl: './employee-form.component.html',
  8. styleUrls: ['./employee-form.component.scss']
  9. })
  10. export class EmployeeFormComponent {
  11. constructor(private employeeService: EmployeeService) {}
  12. public empsArray: Employee[] = [];
  13. newEmployee: any = {}
  14. public empno: number = 0;
  15. public deptno: number = 0;
  16. public firstname: string = '';
  17. public lastname: string = '';
  18. public gender: string = '';
  19. public avatar: string = '';
  20. public job: string = '';
  21. public bio: string = '';
  22. public skills: string = '';
  23. public pickAvatar(event: any) {
  24. let file = event.target.files[0];
  25. this.avatar = file.name;
  26. }
  27. public setAvatar(){
  28. this.newEmployee.avatar = this.avatar.length ? this.avatar : `${this.gender}.png`;
  29. }
  30. public doSkillsArray() {
  31. this.newEmployee.skills = this.skills.split(',');
  32. }
  33. public addEmployee(form: NgForm) {
  34. this.newEmployee = {
  35. empno: this.empno,
  36. deptno: this.deptno,
  37. firstname: this.firstname,
  38. lastname: this.lastname,
  39. gender: this.gender,
  40. avatar: this.avatar,
  41. job: this.job,
  42. bio: this.bio,
  43. skills: this.skills
  44. };
  45. this.setAvatar();
  46. this.doSkillsArray();
  47. this.employeeService.addEmployee(this.newEmployee);
  48. }
  49. }

In employee-form.component.html I have:

  1. <form class="modal-content" #employeeForm="ngForm" (ngSubmit)="addEmployee(employeeForm)">
  2. <!-- Modal Header -->
  3. <div class="modal-header">
  4. <h4 class="modal-title">New employee</h4>
  5. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  6. </div>
  7. <!-- Modal body -->
  8. <div class="modal-body">
  9. <div class="mb-2">
  10. <label class="form-label" for="firstName">First name</label>
  11. <input type="text" class="form-control" name="firstname" id="firstName" placeholder="First name" [(ngModel)]="firstname" />
  12. <div class="invalid-feedback">First name is required.</div>
  13. </div>
  14. <div class="mb-2">
  15. <label class="form-label" for="lastName">Last name</label>
  16. <input type="text" class="form-control" name="lastname" id="lastName" placeholder="Last name" [(ngModel)]="lastname" />
  17. <div class="invalid-feedback">Last name is required.</div>
  18. </div>
  19. <div class="mb-2">
  20. <label class="form-label d-block" for="avatar">Photo</label>
  21. <input type="file" class="file-upload-btn" name="avatar" id="avatar" [(ngModel)]="avatar" (change)="pickAvatar($event)">
  22. </div>
  23. <div class="mb-2">
  24. <label class="form-label" for="job">Job</label>
  25. <input type="text" class="form-control" name="job" id="job" placeholder="Job" [(ngModel)]="job"/>
  26. <div class="invalid-feedback">Job is required.</div>
  27. </div>
  28. <div class="mb-2">
  29. <label class="form-label" for="job">Skills</label>
  30. <input type="text" class="form-control" name="skills" id="skills" placeholder="Skills" [(ngModel)]="skills"/>
  31. </div>
  32. <div class="mb-2">
  33. <label class="form-label" for="department">Department</label>
  34. <select class="form-select" name="department" id="department" [(ngModel)]="deptno">
  35. <option value="10">Management</option>
  36. <option value="20">Sales</option>
  37. <option value="30">Software Engineering</option>
  38. <option value="40">Finance</option>
  39. </select>
  40. </div>
  41. <div class="mb-2">
  42. <label class="form-label d-block">Gender</label>
  43. <div class="form-check form-check-inline">
  44. <input type="radio" class="form-check-input" name="gender" id="mele" value="mele" [(ngModel)]="gender" />
  45. <label class="form-check-label" for="mele">mele</label>
  46. </div>
  47. <div class="form-check form-check-inline">
  48. <input type="radio" class="form-check-input" name="gender" id="femele" value="femele" [(ngModel)]="gender" />
  49. <label class="form-check-label" for="femele">femele</label>
  50. </div>
  51. </div>
  52. <div class="mb-2">
  53. <label class="form-label" for="bio">Bio</label>
  54. <textarea class="form-control" name="bio" id="bio" type="text" placeholder="Bio" [(ngModel)]="bio"></textarea>
  55. <div class="invalid-feedback" data-sb-feedback="bio:required">Bio is required.</div>
  56. </div>
  57. </div>
  58. <!-- Modal footer -->
  59. <div class="modal-footer">
  60. <button type="submit" class="btn btn-success">Add employee</button>
  61. <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
  62. </div>
  63. </form>

In the service employee.service.ts I have:

  1. import { Injectable } from '@angular/core';
  2. import { Observable } from 'rxjs';
  3. import { HttpClient, HttpHeaders } from '@angular/common/http';
  4. import { Employee } from '../models/empModel';
  5. const httpOptions = {
  6. headers: new HttpHeaders({
  7. 'Content-Type': 'application/json'
  8. })
  9. }
  10. @Injectable({
  11. providedIn: 'root'
  12. })
  13. export class EmployeeService {
  14. apiURL: string = 'http://localhost:3000';
  15. employees: Employee[] = [];
  16. constructor(private http: HttpClient) {}
  17. public getEmployees(): Observable<Employee[]>{
  18. return this.http.get<Employee[]>(`${this.apiURL}/employees`);
  19. }
  20. public addEmployee(newEmployee: Employee):Observable<Employee> {
  21. console.log(newEmployee);
  22. return this.http.post<Employee>(`${this.apiURL}/employees`, newEmployee, httpOptions);
  23. }
  24. }

The lineconsole.log(newEmployee) displays the object as expected:

  1. avatar: "mele.png"
  2. bio: "Test"
  3. deptno: "30"
  4. empno: 0
  5. firstname: "John"
  6. gender: "mele"
  7. job: "Programmer"
  8. lastname: "Doe"
  9. skills: (2) ['JavaSctipt', ' Vue']

The problem

Despite the fact that there are no errors and the newEmployee object looks as expected, no new data is added to the employees JSON.

Questions

  1. What am I doing wrong?
  2. What is the most reliable way to fix this issue?

答案1

得分: 0

成功的原因是将this.employeeService.addEmployee(this.newEmployee)替换为

  1. this.employeeService.addEmployee(this.newEmployee).subscribe(
  2. (_response: Employee) => {
  3. console.log("添加成功");
  4. },
  5. (error: HttpErrorResponse) => {
  6. console.log(error.message);
  7. }
  8. );

感谢@user3586286的建议。

英文:

What made it work was replacing this.employeeService.addEmployee(this.newEmployee) with

  1. this.employeeService.addEmployee(this.newEmployee).subscribe(
  2. (_response: Employee) => {
  3. console.log("Added successfully");
  4. },
  5. (error: HttpErrorResponse) => {
  6. console.log(error.message);
  7. }
  8. );

Thanks to @user3586286 for the sugestion.

huangapple
  • 本文由 发表于 2023年6月5日 20:43:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定