【问题标题】:Http request from angular 6 to nodejs从 Angular 6 到 nodejs 的 Http 请求
【发布时间】: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


【解决方案1】:

您需要有权访问您的 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();
});

【讨论】:

  • 嗨@Pato Vargas 我尝试了这两种方法,但没有人为我工作。
  • 手册为我工作。但是进行了一些更改,例如 var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin', 'example.com'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type');下一个(); } ..谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 2021-04-20
  • 2018-04-21
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多