0

I am trying to give a post request to an api with angular .. but it is showing CORS policy error .. If I use CORS google extension, it is working, but how to add access control allow origin header in simple post request?

app.component.html:

<form #userpost="ngForm" (ngSubmit)="onSubmit(userpost.value)">
    <input type="text" name="name" ngModel >
    <input type="email" name="email_id" ngModel >
    <input type="number" name="phone" ngModel >
    
    <input type="number" name="country_code" ngModel >
    <input type="password" name="password" ngModel >
    <input type="text" name="profile" ngModel >
    
    
    <input type="text" name="devicetype" ngModel >
    <input type="date" name="dob" ngModel >
    <input type="type" name="gender" ngModel >
    
    <button type="submit" > SUbmit</button>
    </form>

app.component.ts:

import { Component } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

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

export class AppComponent {
  
  baseURL: string = "MY URl";
 
  title = 'wcart-angular';
  constructor( private http:HttpClient){}

onSubmit(data: any){
console.log(data);


const headers = { 'content-type': 'application/json', 'Access-Control-Allow-Origin': '*','Access-Control-Allow-Credentials': 'true','Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD, OPTIONS'}  ;

    return this.http.post(this.baseURL,{'headers':new HttpHeaders({'Access-Control-Allow-Origin':  '*', 'Access-Control-Allow-Credentials': 'true' || ''})},data).subscribe((result)=>{
      console.log("result",result)
    })
}
}

What httpclintmodule I need to import in app.module.ts?

I'm using angular 11.

Mahmoud Abdelsattar
  • 1,299
  • 1
  • 15
  • 31
  • CORS headers must be set server-side; passing them as request headers on the client side won’t do anything. You’ll need to configure your server to serve the correct CORS headers. [Read more](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). – superhawk610 Mar 25 '21 at 07:27
  • ok..thanks, assume my angular post req page is running in port 4200 and simple node app is listening in port 3000, what i need to do? – raghu raman Mar 25 '21 at 07:32

0 Answers0