0
votes

i am trying to send http request from angular to nodejs server.But in angular side getting error like:

"Access to XMLHttpRequest at 'http://localhost:5030/employees/save' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

and second is "core.js:6014 ERROR Responseheaders: Headers {_headers: Map(0), _normalizedNames: Map(0)}ok: falsestatus: 0statusText: ""type: 3url: null_body: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}__proto__: Body defaultErrorLogger @ core.js:6014

" getting output in nodejs "OPTIONS /employees/save 200 4.957 ms - 4",

Here is my code ,

modal.basic.ts

import {Component} from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { MyserviceService } from './myservice.service';
import { map } from 'rxjs/operators';
import { Http } from '@angular/http';
import {employees} from './employees';
import { HttpClientModule } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'ngbd-modal-basic',
  templateUrl: './modal-basic.html',
  styleUrls: ['./modal-basic.css']
})
export class NgbdModalBasic {
  closeResult: string;
  angfrm : FormGroup
  productForm: FormGroup;
  sellerName:string="";
  name;phone;email;inst;drop;
  sellerId:number=0;
   httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
    })
  };
  // productFormInputs: Product[];
  // @Input()
  // public alerts: Array<IAlert> = [];
  public globalResponse: any;
  constructor(private modalService: NgbModal,private fb: FormBuilder, private service:MyserviceService,private http: Http) {}

  ngOnInit(){
    this.productForm = this.fb.group({
      Name:  ['', Validators.compose([Validators.required, Validators.minLength(3),Validators.maxLength(50)])],
      Phone:['',Validators.compose([Validators.required, Validators.minLength(10),Validators.maxLength(10)])],
      Email: ['', [Validators.required]],
      Drop:['',Validators.required],
      Address:['',Validators.required],
      Datep:['',Validators.required],
      Dated:['',Validators.required],
      Inst:['',''],

    });
  }

  open(content) {
    this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then(() => {
     alert("modalservice");
    });
  }

  OnSaveProduct(value){    
    this.modalService.dismissAll();
    alert("saved");    
    console.log(value.Name);    
    debugger

console.log("data is below");     
return this.http.post("http://localhost:5030/employees/save", this.httpOptions).pipe(     
      map((response) => response.json())).     
        subscribe((data) => console.log(data));    

      this.http.get("http://localhost:5030/").pipe(    
        map((response) => response.json())).    
        subscribe((data) => console.log(data))    
  }

}

myservice.service.ts

import { Injectable } from '@angular/core';    

@Injectable({    
  providedIn: 'root'
})
export class MyserviceService {
serviceProperty = "service created";    
  constructor() { }    
  showTodayDate() {    
     let ndate = new Date();    
     return ndate;    
  }    

  getdata(data:any){
    return data;  
  }
}



and server side save api is like ,
router.post('/save', function(req, res) {
console.log("save api working ");
    debugger
    req.body.other = req.body["other[]"];
    var employee = new Employee(req.body);
    employee.save(function(err, employee) {
        if (err) {
            console.log(err);
            res.render("../views/employees/create");
        } else {
            console.log("Successfully created an employee.");
            debugger
            res.json({ employee: employee });
        }
    });
};
1
Have you enabled/configured CORS support on your nodejs service? If not, do a search for your service + CORS and you will find many materials and/or libraries covering enabling it. - Alexander Staroselsky

1 Answers

0
votes

You need to have access to your nodejs backend. Once you have access to you 2 options with the CORS. To add them manually or adding the cors npm package which is the easiest way.

npm install cors

In your server

const cors = require('cors'); 
app.use(cors());

or manually

//CORS

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  );
  res.setHeader('Access-Control-Allow-Methods', '*');
  next();
});