2

I have a mean stack going. Angular 5.

I'm grabbing data from a form and i'm calling a Service to handle sending the form-data to the backend api.

The service makes use of the HttpClient. It sends off a post request with the correct headers and payload. It successfully posts to the database

BUT... when i look in my console's Network tab, i see 2 identical requests being made! One succeeds because it's the intended request, but the other fails (which is supposed to fail because of duplicate data in db)

I don't understand why 2 requests are being made. I am using the mean stack so (i believe) there shouldn't be any CORS issues.

any ideas?

*UPDATED INFORMATION i checked the Networks tab

  • 1st request has Request Method: POST (200 OK)
  • 2nd request also has Request Method: POST (500)
  • in console tab, 2nd request error coming from zone.js (webpack?)

my form

<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>

in .ts file

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);
      },
      () => {}
    );
  }

}

in service file

   @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);       
     }

    }
2
  • You’re using MEAN stack does not mean you’re not subject to CORS issue. Your Angular still running on its own port. You’re pretty much running into OPTIONS request Commented Feb 3, 2018 at 5:34
  • in my package.json file, i have a script that watches for any changes on my angular code. if any changes are made, it "builds" the code and puts it in the dist file. My server is aware of my dist file and uses the index.html file from there to serve. i don't have a separate terminal running angular on a separate port. Commented Feb 3, 2018 at 14:20

2 Answers 2

7

You declared the submit handler twice, one on your form and and once on your button

Replace

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

with

<button>Register</button>
Sign up to request clarification or add additional context in comments.

1 Comment

This was helpful because I was unable to draw the distinction between a form and Buttom Submit! Thanks
1

One of them is almost certainly the OPTIONS (pre-flight) request. They look similar at a glance.

Take a closer look in the network tab at the actual request method in the header section.

cheers

3 Comments

i checked the network tab, both request methods say "POST". The first one successfully adds data to the db. The second one tries to add data (same payload as 1st), but fails because my db is configured to reject duplicate data
Oh I see. Can you share the code than initiates your service call?
I agree with post below, try not submitting but rather just calling your handler/service.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.