【问题标题】:Access has been blocked by CORS policy访问已被 CORS 策略阻止
【发布时间】:2019-11-01 20:43:31
【问题描述】:

我有一个运行 Angular 应用程序的 Express 服务器(因为我需要服务器端渲染)。

问题是我第一次从应用程序发出请求时一切正常。

当我导航到某个页面并返回请求正常工作的上一个页面时出现问题。当我返回请求不再起作用时,它会显示下一个错误:

从源访问“http://myserver/api/endpoint”处的 XMLHttpRequest 'http://localhost:4000' 已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

我尝试使用 CORS 和其他东西,但它最终给了我同样的错误。

这是我使用 CORS 的部分:

const allowedOrigins = [
  'http://localhost:4000',
  'http://localhost:4200',
  'http://myserver'
];

const corsOptions = {
  origin: function(origin, callback) {
    if (!origin) {
      return callback(null, true);
    }

    if (allowedOrigins.indexOf(origin) === -1) {
      const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }

    return callback(null, true);
  },
  credentials: true,
  optionsSuccessStatus: 200,
  methods: 'GET,PUT,POST,OPTIONS',
  allowedHeaders: 'Content-Type,Authorization'
};

app.use(cors(corsOptions));

在没有 CORS 的情况下也尝试过:

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-Type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

那么,第一次有效,第二次无效可能是什么问题?

这是否与快速控制台中的此错误有关:'ERROR TypeError: spanEl.getBoundingClientRect is not a function'?

【问题讨论】:

  • 在所有行中使用 res.setHeader 而不是 res.header 还添加 Authorization
  • @JoelJoseph 试过了,没用

标签: angular express cors


【解决方案1】:

对您的代码进行一些更改:

app.use(function (req, res, next) {

    // website you wish to  allow to connet    
    res.setHeader('Access-Control-Allow-Origin','*');

    // request method you wish to allow
    res.setHeader('Access-Control-Allow-Methods','GET, POST, OPTION, PUT, PATCH, DELETE');

    // request headers you wish to allow 
    res.setHeader('Access-Control-Allow-Headers','X-Requested-With,content-type,Authorization');   

    // set to true if you need the website to include  cookies  in the  request  sent 
    // to the API (eg. in case you can see sessions )
    res.setHeader('Access-Control-Allow-Credentials','false');

    // pass to the next layer of middleware
    next();

});

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 2019-04-28
    • 2019-12-18
    • 2023-01-14
    • 2021-10-27
    • 2021-10-05
    • 2021-03-18
    • 2022-08-14
    • 2021-01-07
    相关资源
    最近更新 更多