Я пытаюсь отправить http-запрос с angular на сервер nodejs. Но с угловой стороны получаю ошибку вроде:
" Доступ к XMLHttpRequest по адресу http://localhost:5030/employees/save' от источника 'http://localhost:4200' было заблокировано политикой CORS: Ответ на запрос предварительной проверки не проходит проверку контроля доступа: в запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin»."
и второй: " core.js: 6014 ОШИБКИ Ответа: Заголовки {_headers: Map (0), _normalizedNames: Map (0)} ok: falsestatus: 0statusText:" "Тип: 3url: null_body: ProgressEvent {isTrusted:true, lengthComputable: false, загружено: 0, всего: 0, тип: "error",…} __ proto__: Body defaultErrorLogger @ core.js: 6014
"получение вывода в nodejs "ОПЦИИ / сотрудники / экономия 200 4,997 мс - 4 ",
Вот мой код,
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 });
}
});
};