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

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

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:

{
  "employees": [
    {
      "empno": "2",
      "deptno": "10",
      "firstname": "Sandy",
      "lastname": "Paton",
      "gender": "femele",
      "avatar": "sandy.png",
      "job": "Manager",
      "bio": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam obcaecati veritatis maiore.",
      "skills": [
        "Management"
      ]
    },
    {
      "empno": "4",
      "deptno": "30",
      "firstname": "Hollie",
      "lastname": "Haerr",
      "gender": "femele",
      "avatar": "hollie.png",
      "job": "Programmer",
      "bio": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam obcaecati veritatis maiore.",
      "skills": [
        "HTML5",
        "CSS3",
        "JavaScript",
        "Angular 2+"
      ]
    },
    {
      "empno": "6",
      "deptno": "30",
      "firstname": "Lynde",
      "lastname": "Ailyn",
      "gender": "femele",
      "avatar": "femele.png",
      "job": "Programmer",
      "bio": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam obcaecati veritatis maiore.",
      "skills": [
        "HTML5",
        "CSS3",
        "JavaScript",
        "Angular 2+"
      ]
    }
  ]
}

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:

import { Component } from '@angular/core';
import { Employee } from '../../models/empModel';
import { EmployeeService } from '../../services/employee.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-employee-form',
  templateUrl: './employee-form.component.html',
  styleUrls: ['./employee-form.component.scss']
})

export class EmployeeFormComponent {

  constructor(private employeeService: EmployeeService) {}

  public empsArray: Employee[] = [];

  newEmployee: any = {}

  public empno: number = 0;
  public deptno: number = 0;
  public firstname: string = '';
  public lastname: string = '';
  public gender: string = '';
  public avatar: string = '';
  public job: string = '';
  public bio: string = '';
  public skills: string = ''; 

  public pickAvatar(event: any)  {
	let file = event.target.files[0];
	this.avatar = file.name;
  }

  public setAvatar(){
	this.newEmployee.avatar = this.avatar.length ? this.avatar : `${this.gender}.png`;
  }

  public doSkillsArray()  {
	this.newEmployee.skills = this.skills.split(',');
  }
  
  public addEmployee(form: NgForm) {

	this.newEmployee = {
	  empno: this.empno,
	  deptno: this.deptno,
	  firstname: this.firstname,
	  lastname: this.lastname,
	  gender: this.gender,
	  avatar: this.avatar,
	  job: this.job,
	  bio: this.bio,
	  skills: this.skills
	};

	this.setAvatar();

	this.doSkillsArray();

	this.employeeService.addEmployee(this.newEmployee);
  }

}

In employee-form.component.html I have:

<form class="modal-content" #employeeForm="ngForm" (ngSubmit)="addEmployee(employeeForm)">

    <!-- Modal Header -->
    <div class="modal-header">
      <h4 class="modal-title">New employee</h4>
      <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
    </div>

    <!-- Modal body -->
    <div class="modal-body">
      <div class="mb-2">
          <label class="form-label" for="firstName">First name</label>
          <input type="text" class="form-control" name="firstname" id="firstName" placeholder="First name" [(ngModel)]="firstname" />
          <div class="invalid-feedback">First name is required.</div>
      </div>
      <div class="mb-2">
          <label class="form-label" for="lastName">Last name</label>
          <input type="text" class="form-control" name="lastname" id="lastName" placeholder="Last name" [(ngModel)]="lastname" />
          <div class="invalid-feedback">Last name is required.</div>
      </div>
      <div class="mb-2">
        <label class="form-label d-block" for="avatar">Photo</label>
        <input type="file" class="file-upload-btn" name="avatar" id="avatar" [(ngModel)]="avatar" (change)="pickAvatar($event)">
      </div>
      <div class="mb-2">
          <label class="form-label" for="job">Job</label>
          <input type="text" class="form-control" name="job" id="job" placeholder="Job" [(ngModel)]="job"/>
          <div class="invalid-feedback">Job is required.</div>
      </div>
      <div class="mb-2">
        <label class="form-label" for="job">Skills</label>
        <input type="text" class="form-control" name="skills" id="skills" placeholder="Skills" [(ngModel)]="skills"/>
    </div>
      <div class="mb-2">
        <label class="form-label" for="department">Department</label>
        <select class="form-select" name="department" id="department" [(ngModel)]="deptno">
          <option value="10">Management</option>
          <option value="20">Sales</option>
          <option value="30">Software Engineering</option>
          <option value="40">Finance</option>
        </select>
    </div>
      <div class="mb-2">
          <label class="form-label d-block">Gender</label>
          <div class="form-check form-check-inline">
              <input type="radio" class="form-check-input" name="gender" id="mele" value="mele" [(ngModel)]="gender" />
              <label class="form-check-label" for="mele">mele</label>
          </div>
          <div class="form-check form-check-inline">
              <input type="radio" class="form-check-input"  name="gender" id="femele" value="femele" [(ngModel)]="gender" />
              <label class="form-check-label" for="femele">femele</label>
          </div>
      </div>

      <div class="mb-2">
          <label class="form-label" for="bio">Bio</label>
          <textarea class="form-control" name="bio" id="bio" type="text" placeholder="Bio" [(ngModel)]="bio"></textarea>
          <div class="invalid-feedback" data-sb-feedback="bio:required">Bio is required.</div>
      </div>
    </div>

    <!-- Modal footer -->
    <div class="modal-footer">
      <button type="submit" class="btn btn-success">Add employee</button>
      <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
    </div>
  </form>

In the service employee.service.ts I have:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Employee } from '../models/empModel';

const httpOptions = {
  headers: new HttpHeaders({
	'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  apiURL: string = 'http://localhost:3000';

  employees: Employee[] = [];

  constructor(private http: HttpClient) {}

  public getEmployees(): Observable<Employee[]>{
	return this.http.get<Employee[]>(`${this.apiURL}/employees`);
  }

  public addEmployee(newEmployee: Employee):Observable<Employee> {
	console.log(newEmployee);
	return this.http.post<Employee>(`${this.apiURL}/employees`, newEmployee, httpOptions);
  }
}

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

avatar: "mele.png"
bio: "Test"
deptno: "30"
empno: 0
firstname: "John"
gender: "mele"
job: "Programmer"
lastname: "Doe"
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)替换为

this.employeeService.addEmployee(this.newEmployee).subscribe(
  (_response: Employee) => {
    console.log("添加成功");
  },
  (error: HttpErrorResponse) => {
    console.log(error.message);
  }
);

感谢@user3586286的建议。

英文:

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

this.employeeService.addEmployee(this.newEmployee).subscribe(
  (_response: Employee) => {
    console.log("Added successfully");
  },
  (error: HttpErrorResponse) => {
    console.log(error.message);
  }
);

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:

确定