【发布时间】:2019-10-10 20:50:12
【问题描述】:
我正在尝试将 http 请求从 angular 发送到 nodejs 服务器。但是在 angular 端出现如下错误:
"从源 'http://localhost:4200' 访问 XMLHttpRequest 在 'http://localhost:5030/employees/save' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-请求的资源上存在 Origin' 标头。"
第二个是“core.js:6014 ERROR Responseheaders: Headers {_headers: Map(0), _normalizedNames: Map(0)}ok: falsestatus: 0statusText: ""type: 3url: null_body: ProgressEvent { isTrusted:true,lengthComputable:false,加载:0,总数:0,类型:“错误”,...}__proto__:正文 defaultErrorLogger@core.js:6014
" 在nodejs中获取输出“OPTIONS /employees/save 200 4.957 ms - 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 });
}
});
};
【问题讨论】:
-
您是否在 nodejs 服务上启用/配置了 CORS 支持?如果没有,请搜索您的服务 + CORS,您会发现许多材料和/或库涵盖启用它。
标签: node.js angular httpclient