【问题标题】:Angular client enable CORSAngular 客户端启用 CORS
【发布时间】:2019-01-09 10:24:18
【问题描述】:

CORS 在服务器上很好,可以按预期工作。我尝试使用角度 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 .....

【问题讨论】:

标签: node.js angular express cors


【解决方案1】:

为了将来的参考,帮助我的是“大卫”的回答,在所有路由之前没有添加 cors。

"..... 意思是,在定义路由之前。" 所以就在...之后 var app = express();

我只是用... app.use(cors());

【讨论】:

    【解决方案2】:

    您不需要在 Angular 中启用 cors,这是服务器端问题。见:

    https://stackoverflow.com/a/29548846/4461537

    【讨论】:

      【解决方案3】:

      一点介绍:

      跨域资源共享aka CORS 是一种使用附加 HTTP 标头 告诉浏览器让在一个来源(例如http://localhost:3000)运行的Web 应用程序访问来自不同来源(例如http://localhost:8080)的选定资源。换句话说,当 Web 应用程序请求的资源与其自己的来源(域、协议或端口)不同时,它会执行跨域 HTTP 请求。出于安全原因,浏览器会限制从脚本发起的跨域 HTTP 请求。

      Access-Control-Allow-Origin 标头确定允许哪些来源通过 CORS 访问服务器资源。


      如何解决 CORS 问题?

      您可以通过创建Express 中间件自己完成。这是相应的代码sn-p:

      // 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。

      【讨论】:

        猜你喜欢
        • 2015-06-24
        • 2015-08-25
        • 2018-10-26
        • 2018-03-30
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        • 2016-10-12
        • 2020-05-22
        相关资源
        最近更新 更多