【问题标题】:Angular makes http request TwiceAngular 两次发出 http 请求
【发布时间】:2018-07-13 14:54:45
【问题描述】:

我有一个平均堆栈。角 5。

我正在从表单中获取数据,并正在调用服务来处理将表单数据发送到后端 api。

该服务使用 HttpClient。它使用正确的标头和有效负载发送发布请求。它成功发布到数据库

但是...当我查看控制台的“网络”选项卡时,我看到 2 个相同的请求正在发出!一个成功,因为它是预期的请求,但另一个失败(由于 db 中的重复数据而应该失败)

我不明白为什么要发出 2 个请求。我使用的是平均堆栈,所以(我相信)不应该有任何 CORS 问题。

有什么想法吗?

*更新信息 我检查了网络标签

  • 第一个请求具有请求方法:POST (200 OK)
  • 第二个请求也有请求方法:POST (500)
  • 在控制台选项卡中,来自 zone.js(webpack?)的第二个请求错误

我的表格

<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
  <div class="form-group">
    <label for="username">Username</label>
    <input 
      type="text" 
      id="username"
      class="form-control"
      formControlName="username"
      placeholder="username" >
  </div>
  <div class="form-group">
    <label for="email">Email</label>
    <input 
      type="email" 
      id="email"
      class="form-control"
      formControlName="email"
      placeholder="email" >
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input 
      type="password" 
      id="password"
      class="form-control"
      formControlName="password"
      placeholder="password" >
  </div>
  <div class="form-group">
    <label for="name">Restaurant Name</label>
    <input 
      type="text" 
      id="name"
      class="form-control"
      formControlName="name"
      placeholder="Restaurant Name" >
  </div>    
  <div class="form-group">
    <label for="url">Restaurant Url <br> <small class="form-text text-
    muted">A link that will take patrons to your list of available food 
    items</small></label>
    <input 
          type="text" 
          id="url"
          class="form-control form-contol-sm"
          formControlName="url"
          placeholder="RosasPizza123" >

  </div>
  <div class="form-group">
    <label for="address">Address</label>
    <input 
      type="text" 
      id="address"
      class="form-control"
      formControlName="address"
      placeholder="125 Address st" >
  </div>
  <div class="form-group">
    <label for="city">City/Town</label>
    <input 
      type="text" 
      id="city"
      class="form-control"
      formControlName="city"
      placeholder="Newburgh" >
  </div>
  <div class="form-group">
    <label for="state">State</label>
    <input 
      type="text" 
      id="state"
      class="form-control"
      formControlName="state"
      placeholder="NY"
      maxlength="2" >
  </div>
  <div class="form-group">
    <label for="zipcode">Zipcode</label>
    <input 
      type="text" 
      id="zipcode"
      class="form-control"
      formControlName="zipcode"
      placeholder="zipcode" >
  </div>
  <div class="form-group">
    <label for="phone">Phone</label>
    <input 
        type="tel" 
        id="phone"
        class="form-control"
        formControlName="phone"
        placeholder="phone" >
    </div>
    <button (click)="onSubmit()">Register</button>  
</form>

在 .ts 文件中

export class RegisterComponent implements OnInit {
  registerForm: FormGroup;

  constructor( private userService: UserService) { }

  ngOnInit() {    
    this.registerForm = new FormGroup({
      'username': new FormControl(null, Validators.required),
      'email': new FormControl(null, [
              Validators.required,
              Validators.email]),
      'password': new FormControl(null, Validators.required),
      'name': new FormControl(null, Validators.required),
      'url': new FormControl(null, Validators.required),
      'address': new FormControl(null, Validators.required),
      'city': new FormControl(null, Validators.required),
      'state': new FormControl(null, [
              Validators.required,
              Validators.maxLength(2)]),
      'zipcode': new FormControl(null, Validators.required),
      'phone': new FormControl(null),
   });
  }

onSubmit() {        
  const newUser = new User(
    this.registerForm.value.username,
    this.registerForm.value.email,
    this.registerForm.value.password,
    this.registerForm.value.name,
    this.registerForm.value.url,
    this.registerForm.value.address,
    this.registerForm.value.city,
    this.registerForm.value.state,
    this.registerForm.value.zipcode,
    this.registerForm.value.phone
  );

this.userService.register(newUser)
    .subscribe(
      (response) => {

        console.log("response", response);
      },
      () => {}
    );
  }

}

在服务文件中

   @Injectable()
   export class UserService {
     url = 'http://localhost:3000/api/';

     constructor(private http: HttpClient) {}

    // register user
     register(user: User) {
        const userString = JSON.stringify(user);
        const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json'
                // auth: 'my-token'
            })
        };
        return this.http.post(this.url + 'register', userString, httpOptions);       
     }

    }

【问题讨论】:

  • 您使用 MEAN 堆栈并不意味着您不受 CORS 问题的影响。您的 Angular 仍在其自己的端口上运行。您几乎遇到了 OPTIONS 请求
  • 在我的 package.json 文件中,我有一个脚本可以监视我的角度代码的任何变化。如果进行了任何更改,它会“构建”代码并将其放入 dist 文件中。我的服务器知道我的 dist 文件并使用 index.html 文件从那里提供服务。我没有在单独的端口上运行角度的单独终端。

标签: angular http mean-stack angular5 angular2-http


【解决方案1】:

其中一个几乎可以肯定是 OPTIONS(飞行前)请求。乍一看,它们看起来很相似。

在网络选项卡中仔细查看标题部分中的实际请求方法。

干杯

【讨论】:

  • 我检查了网络选项卡,两种请求方法都说“POST”。第一个成功地将数据添加到数据库。第二个尝试添加数据(与第一个相同的有效负载),但由于我的数据库配置为拒绝重复数据而失败
  • 哦,我明白了。您可以共享代码而不是启动您的服务调用吗?
  • 我同意下面的帖子,尽量不要提交,而只是调用你的处理程序/服务。
【解决方案2】:

您两次声明了提交处理程序,一次在您的表单上,一次在您的按钮上

替换

<button (click)="onSubmit()">Register</button>

<button>Register</button>

【讨论】:

  • 这很有帮助,因为我无法区分表单和按钮提交!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多