【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource. Access to XMLHttpRequest has been blocked by CORS plicy请求的资源上不存在“Access-Control-Allow-Origin”标头。 CORS plicy 已阻止对 XMLHttpRequest 的访问
【发布时间】:2020-10-11 10:00:45
【问题描述】:

我正在使用 angular 和 nodejs 构建电子商务,当我尝试获取产品时出现此错误: **从源“http://localhost:4200”访问“http://localhost:3000/api/products?limit=10”的 XMLHttpRequest 已被 CORS 策略阻止:无“访问控制允许源” ' 请求的资源上存在标头。 ** 我已经安装了 cors 并在后端的 app.js 文件中使用了它。 这是我的代码:

export class HomeComponent implements OnInit {

  products: any[] = [];


  constructor(private productService: ProductService,
              private router: Router) {
  }

  ngOnInit(): void {
    this.productService.getAllProducts().subscribe((prods: { count: Number, products: any[] }) => {
      this.products = prods.products;
    });
  }

  selectProduct(id: Number) {
    this.router.navigate(['/product', id]).then();
  }
}

这是我的 home.component.ts

export class ProductService {

  private SERVER_URL = environment.SERVER_URL;
  constructor(private http: HttpClient) { }

  /* This is to fetch all products from the backend server */
  getAllProducts(numberOfResults= 10) {
    return this.http.get(this.SERVER_URL + '/products', {
      params: {
        limit: numberOfResults.toString()
      }
    });
  }

}

这是我的 product.service.ts

【问题讨论】:

    标签: node.js angular typescript


    【解决方案1】:

    您需要在您的应用程序中允许跨域,这意味着哪些网站可以与您的后端应用程序进行通信,在此另一个网站将是位于 localhost:4200 的前端,您可以通过输入以下内容来允许它在你的 Nodejs 应用中

    const express = require("express");
    const app = express();
    app.use((req, res, next) => {
      res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
      res.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
      if (req.method == "OPTIONS") {
        return res.sendStatus(200);
      }
      next();
    });
    

    如您所见,上面的代码设置标题以允许 CORS。

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2020-04-15
      • 2020-06-24
      • 1970-01-01
      • 2021-04-14
      • 2020-08-30
      • 2023-04-07
      • 2021-06-30
      • 2020-12-13
      相关资源
      最近更新 更多