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).如何在此请求上启用CORS请.....

发布于 2018-08-02 14:25:35
对于将来的参考,是"Davids“的答案帮助了我,cors没有在所有路由之前添加。
".....意思是在定义路由之前。“所以紧接着..。var app = express();
我只是用..。app.use(cors());
发布于 2018-08-02 02:44:47
你不需要在angular中启用cors,这是一个服务器端的问题。请参见:
发布于 2018-08-02 03:22:19
简单介绍一下:
跨域资源共享,也称为CORS是一种机制,它使用额外的 headers来告诉浏览器给予在一个源(例如http://localhost:3000)上运行的web应用程序从另一个源(例如http://localhost:8080)访问所选资源的权限。换句话说,当web应用程序请求的资源来源(域、协议或端口)不同于它自己的资源时,它将执行跨域HTTP请求。出于安全考虑,浏览器会限制从脚本发起的跨域HTTP请求。
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在依赖它的任何其他控制器/路由/中间件之前被启用。
https://stackoverflow.com/questions/51640206
复制相似问题