【问题标题】:How to use REST with Node.js and AngularJS being on different port?如何将 REST 与 Node.js 和 AngularJS 一起使用在不同的端口上?
【发布时间】:2013-03-09 07:00:55
【问题描述】:

我正在尝试了解 Angular 和 Node.js 在后端的合作。但是我不知道如何使用 REST 在两者之间进行数据传输。

我有:

  1. Node.js 后端在端口 8000 上运行,响应各种 GET 和 POST 请求(通过 cURL)。
  2. Angular 前端通过 Apache 加载,在端口 80 上运行。

JavaScript 控制台自然会将其识别为not allowed by Access-Control-Allow-Origin

这通常是如何解决的?我做错了吗?我不应该通过 Apache 运行前端吗?

【问题讨论】:

    标签: javascript apache node.js rest angularjs


    【解决方案1】:

    您也可以使用 cors

    npm install cors

    const cors = require('cors');
    
    app.use(cors({
        origin: 'http://example.com'
    }));
    

    http://example.com 是您在前端的应用程序源/域。

    【讨论】:

      【解决方案2】:

      将此添加到您的 Node.js API 服务器

      server.all('*', function(req, res, next) {
          res.header("Access-Control-Allow-Origin", "*");
          res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
          res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
          if ('OPTIONS' == req.method) {
              return res.send(200);
          }
          next();
      });
      

      【讨论】:

        【解决方案3】:

        解决它的一种方法是使用Cross-origin Resource Sharing。浏览器支持也不错。

        【讨论】:

        • 没有更清洁的方法吗?肯定有很多页面使用 Ang + Node,不要告诉我他们是这样做的:-O
        • 您可以通过同一个代理代理两个应用程序,但使用不同的上下文。
        • 得到它与backbonetutorials.com/cross-domain-sessions一起工作感谢您指出,怎么做!
        猜你喜欢
        • 2018-01-14
        • 2013-09-19
        • 1970-01-01
        • 2015-04-28
        • 2015-01-14
        • 2013-01-17
        • 1970-01-01
        • 2020-08-23
        • 1970-01-01
        相关资源
        最近更新 更多