角度6到nodejs的Http请求"/>
[从角度6到nodejs的Http请求
我正在尝试将来自HTTP的请求从angular发送到nodejs服务器。但是在angular方面却出现了类似的错误:
“ 从原点'http://localhost:5030/employees/save'到'http://localhost:4200'的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-Origin'标头出现在请求的资源上。“
其次是“ core.js:6014错误响应标头:标头{_headers:Map(0),_normalizedNames:Map(0)} ok:falsestatus:0statusText:”“ type:3url:null_body:ProgressEvent。{isTrusted: true,lengthComputable:false,已加载:0,总计:0,类型:“ error”,…} __ 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: ['', Validatorspose([Validators.required, Validators.minLength(3),Validators.maxLength(50)])],
Phone:['',Validatorspose([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的2个选项。要手动添加它们或添加cors npm软件包,这是最简单的方法。
npm install cors
在您的服务器中
const cors = require('cors');
app.use(cors());
或手动
// 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();
});
更多推荐
[从角度6到nodejs的Http请求
发布评论