[英]How to fix ''http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.'
[英]No 'Access-Control-Allow-Origin' header is present on the requested resource. Access to XMLHttpRequest has been blocked by CORS plicy
我正在 angular 和 nodejs 中構建電子商務,當我嘗試獲取產品時出現此錯誤:**Access to XMLHttpRequest at 'http://localhost:3000/api/products?limit=10' from origin “http://localhost:4200”已被 CORS 策略阻止:請求的資源上不存在“Access-Control-Allow-Origin”header。 ** 我已經安裝了 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
你需要在你的應用程序中允許跨域,這意味着哪些網站可以與你的后端應用程序通信,在這個另一個網站將是前端,它位於 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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.