[英]Angular client enable CORS
CORS 在服务器上很好,并且按预期工作。 我尝试使用 angular HTTPClient 向服务器的 REST API 发送请求,但收到 CORS 错误。 如果在服务器上启用了 CORS,为什么会出现此错误? 客户端应该没问题吧?
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/blah/blah (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
为了将来参考,“Davids”的回答对我有帮助,在所有路由之前都没有添加 cors。
“..... 意思是,在定义路线之前。” 所以就在... var app = express();
我只是使用... app.use(cors());
您不需要在 angular 中启用 cors,这是服务器端问题。 看:
跨源资源共享又名CORS是一种机制,它使用额外的HTTP 标头来告诉浏览器为在一个源(例如http://localhost:3000
)上运行的 Web 应用程序提供对来自不同源(例如http://localhost:8080
)。 换句话说,当 Web 应用程序请求与自身具有不同来源(域、协议或端口)的资源时,它会执行跨源 HTTP 请求。 出于安全原因,浏览器会限制从脚本发起的跨域 HTTP 请求。
Access-Control-Allow-Origin
标头确定Access-Control-Allow-Origin
哪些源通过 CORS 访问服务器资源。
如何解决 CORS 问题?
您可以通过创建Express
中间件自己来完成。 这是适当的代码片段:
// Enable CORS for specific origins:
app.use((req, res, next) => {
// Allow multiple predefined origins
const allowedOrigins = ["https://deployed-app.com", "http://localhost:3000"];
const origin = req.headers.origin; // extract the origin from the header
if (allowedOrigins.indexOf(origin) > -1) { // if the origin is present in our array
res.setHeader("Access-Control-Allow-Origin", origin); // set the CORS header on the response
}
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next(); // move on to the next middleware
});
或者,您可以接受所有请求,但此选项仅适用于您正在开发中或您的 API 是公开的 :)
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
此外,还有一个Express
CORS 中间件,这是您使用它的方式:
npm install cors --save
启用所有 CORS 请求:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`CORS-enabled server is up on ${port}`);
});
为单个路由启用 CORS
const express = require('express');
const cors = require('cors');
const app = express();
app.get('/products/:id', cors(), (req, res, next) => {
res.json({msg: 'This is CORS-enabled for a Single Route'})
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`CORS-enabled server is up on ${port}`);
});
重要问题:对于 Express 中间件,顺序非常重要。 因此,请确保在可能依赖于它的任何其他控制器/路由/中间件之前启用 CORS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.