-1

I have a MEAN Stack web application where I am trying to register users. If I use Insomnia/Postman to make the POST request I successfully register the user. However, when I send the request from Angular 10, I get an empty request body {}. I also printed the data in Angular service to see what I am sending and the data is present. I don't understand why it works with Insomnia/Postman and not with Angular.

Here is the Angular code:

signup.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from 'src/app/services/authentication.service';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit {

  constructor(private router: Router, private authenticationService: AuthenticationService) { }

  ngOnInit() {
  }

  submitSignUpForm(data) {
    var formData = new FormData()
    formData.append('email', data.email)
    formData.append('password', data.password)
    formData.append('fullname', data.firstname + ' ' + data.lastname)      
    this.authenticationService.registerUser(formData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }
}

authentication.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  serverURL = ""

  constructor(private http: HttpClient) {
    this.serverURL = <SERVER_URL>
  }

  registerUser(data) {
    return this.http.post(`${this.serverURL}/auth/register`, data)
  }
}

server.js

....

app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: true
}))
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.urlencoded({extended: true}))
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

....

Let me know if you need more information.

npatel
  • 181
  • 1
  • 12

1 Answers1

0

I found a solution from the post Angular 7 not sending HTTP Post request data

I added this to authentication.service.ts

import { HttpHeaders } from '@angular/common/http';

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

And added httpOptions as third parameter to post request

npatel
  • 181
  • 1
  • 12