【问题标题】:CORS error with the Access-Controll-Allow-Origin * - NodeJS and AngularAccess-Control-Allow-Origin *的CORS错误 - NodeJS和Angular
【发布时间】:2020-06-02 00:28:16
【问题描述】:

我正在使用 Angular 做一个网络应用程序,当我将后端与前端连接时,它给了我一个 CORS 错误: Access to XMLHttpRequest at 'http://localhost:3700/api/save-project' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我知道 CORS 是什么,但我不知道为什么会出现这个错误,因为在后端的 app.js 中,我有阻止 CORS 的代码

我该如何解决这个问题?

代码:

app.js '使用严格'

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

// cargar archivo Rutas
var routes = require('./routes/product');

// Middlewares
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json()); // Content-Type: image/jpg

// Configurar cabeceras y cors
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

// Rutas
app.use('/api', routes);

// exportar
module.exports = app;

Angular 中的组件:

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/products.service';
import { Product } from 'src/app/models/product';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'crear',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
  providers: [HttpClient, ProductService]
})
export class CreateComponent implements OnInit {
  public producto: Product;
  public product: any;

   constructor(
    //,
    //private http: HttpClient
    private _productService: ProductService
  ) { 
    this.producto = new Product('','','','',2,2);
  }

  ngOnInit(): void {
  }

  onSubmit(form){
    this._productService.saveProduct(this.producto).subscribe(
      response => {
        if(response.producto){

          form.reset();

          this.product = this.producto._id;
        }else{
        alert("No se ha podido");
      };
      } 
    )
  }

}

服务:

import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Product } from '../models/product';
import { Global } from './global.service';

@Injectable()
export class ProductService{
    public url: String;

    constructor(
        private _http: HttpClient
    ){
        this.url = Global.url;
    }

    saveProduct(product: Product): Observable<any>{
        var params = JSON.stringify(product);
        let headers =  new HttpHeaders().set('Content-Type', 'application/json');

        return this._http.post(this.url+'save-project', params, {headers: headers});
    }
}

谢谢大家

【问题讨论】:

  • 使用 Express CORS 包
  • 谢谢,但还有其他错误Failed to load resource: net::ERR_CONNECTION_REFUSED

标签: node.js angular mongodb express


【解决方案1】:

在您的后端项目中安装 cors 中间件:

npm install cors --save

然后,在 app.js 中,导入 cors 包并使用:

var cors = require('cors');

var app = express();

app.use(cors());

在任何路由声明之前应用 cors 中间件很重要。

更多关于 cors 中间件的信息:https://github.com/expressjs/cors#readme

更多关于cors的信息:https://developer.mozilla.org/es/docs/Web/HTTP/Access_control_CORS

【讨论】:

    【解决方案2】:

    您可以使用 cors (https://www.npmjs.com/package/cors) 来处理 cors 设置。请遵循文档中的用法。 如果您不想启用 cors origin,并且只需要在本地开发中使用此功能,您可以尝试使用 --disable-web-security 模式启动 chrome。

    【讨论】:

      【解决方案3】:

      尝试在 app.js 中设置 CORS 标头后添加这些 if 语句 (我在 graphQL 中需要这个,希望它可以工作!)

      if (req.method === "OPTIONS") {
          res.send(200);
        }
      
      app.use((req, res, next) => {
          res.header('Access-Control-Allow-Origin', '*');
          res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
          res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
          res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
        if (req.method === "OPTIONS") {
          res.send(200);
        }
          next();
      });
      

      【讨论】:

        猜你喜欢
        • 2016-09-30
        • 2014-08-11
        • 2020-06-03
        • 2021-06-17
        • 2017-10-24
        • 2013-06-13
        • 2015-08-17
        • 2021-05-12
        • 1970-01-01
        相关资源
        最近更新 更多