首页 文章

否'Access-Control-Allow-Origin' - 节点/ Apache端口问题

提问于
浏览
197

我使用Node / Express创建了一个小API并尝试使用Angularjs来提取数据,但是当我的html页面在localhost:8888上的apache下运行并且节点API在端口3000上侦听时,我得到了No'Access-Control-允许来源 . 我尝试使用node-http-proxy和Vhosts Apache但没有取得多大成功,请参阅下面的完整错误和代码 .

“XMLHttpRequest无法加载localhost:3000 . 请求的资源上没有'Access-Control-Allow-Origin'标头 . 因此不允许来自”localhost:8888“ . ”

// Api Using Node/Express    
var express = require('express');
var app = express();
var contractors = [
    {   
     "id": "1", 
        "name": "Joe Blogg",
        "Weeks": 3,
        "Photo": "1.png"
    }
];

app.use(express.bodyParser());

app.get('/', function(req, res) {
  res.json(contractors);
});
app.listen(process.env.PORT || 3000);
console.log('Server is running on Port 3000')


    // Angular code
    angular.module('contractorsApp', [])
    .controller('ContractorsCtrl', function($scope, $http,$routeParams) {

   $http.get('localhost:3000').success(function(data) {

    $scope.contractors = data;

   })

   // HTML
   <body ng-app="contractorsApp">
    <div ng-controller="ContractorsCtrl"> 
        <ul>
         <li ng-repeat="person in contractors">{{person.name}}</li>
        </ul>
    </div>
   </body>

10 回答

  • 24
    //Add following code in app.js of NODEJ Restful api to avoid "Access-Control-Allow-Origin" error in angular 6 or any other framework
    
    var express = require('express');
    var app = express();
    
    var cors = require('cors');
    var bodyParser = require('body-parser');
    
    //enables cors
    app.use(cors({
      'allowedHeaders': ['sessionId', 'Content-Type'],
      'exposedHeaders': ['sessionId'],
      'origin': '*',
      'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
      'preflightContinue': false
    }));
    
  • 1

    另一种方法是简单地将 Headers 添加到您的路线:

    router.get('/', function(req, res) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
        res.setHeader('Access-Control-Allow-Credentials', true); // If needed
    
        res.send('cors problem fixed:)');
    });
    
  • 503

    你可以使用“$ http.jsonp”

    要么

    以下是针对本地测试使用chrome的方法

    您需要使用以下命令打开chrome . (按窗口R)

    Chrome.exe --allow-file-access-from-files
    

    注意:您的chrome不能打开 . 运行此命令时,chrome将自动打开 .

    如果要在命令提示符下输入此命令,请选择chrome安装目录,然后使用此命令 .

    下面是MAC中打开chrome的脚本代码,带有“--allow-file-access-from-files”

    set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" 
    set switch to " --allow-file-access-from-files"
    do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"
    

    第二种选择

    您可以使用open(1)添加标志:open -a 'Google Chrome' --args --allow-file-access-from-files

  • 70

    在项目中安装cors依赖项:

    npm i --save cors
    

    将以下内容添加到服务器配置文件中:

    var cors = require('cors');
    app.use(cors());
    

    它适用于我的2.8.4 cors版本 .

  • 0

    接受的答案很好,如果你喜欢更短的东西,你可以使用一个名为 cors 的插件,可用于Express.js

    对于这种特殊情况,它使用起来很简单:

    var cors = require('cors');
    
    // use it before all route definitions
    app.use(cors({origin: 'http://localhost:8888'}));
    
  • 1
    app.all('*', function(req, res,next) {
        /**
         * Response settings
         * @type {Object}
         */
        var responseSettings = {
            "AccessControlAllowOrigin": req.headers.origin,
            "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
            "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
            "AccessControlAllowCredentials": true
        };
    
        /**
         * Headers
         */
        res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
        res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
        res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
        res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
    
        if ('OPTIONS' == req.method) {
            res.send(200);
        }
        else {
            next();
        }
    
    
    });
    
  • 2

    尝试将以下中间件添加到您的NodeJS / Express应用程序中(为方便起见,我添加了一些注释):

    // Add headers
    app.use(function (req, res, next) {
    
        // Website you wish to allow to connect
        res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
    
        // Request methods you wish to allow
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
        // Request headers you wish to allow
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
        // Set to true if you need the website to include cookies in the requests sent
        // to the API (e.g. in case you use sessions)
        res.setHeader('Access-Control-Allow-Credentials', true);
    
        // Pass to next layer of middleware
        next();
    });
    

    希望有所帮助!

  • 5

    答案代码仅允许localhost:8888 . 此代码无法部署到 生产环境 环境,或者不同的服务器和端口名称 .

    要使其适用于所有来源,请使用此代码:

    // Add headers
    app.use(function (req, res, next) {
    
        // Website you wish to allow to connect
        res.setHeader('Access-Control-Allow-Origin', '*');
    
        // Request methods you wish to allow
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
        // Request headers you wish to allow
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
        // Set to true if you need the website to include cookies in the requests sent
        // to the API (e.g. in case you use sessions)
        res.setHeader('Access-Control-Allow-Credentials', true);
    
        // Pass to next layer of middleware
        next();
    });
    
  • 10

    top answer对我来说很好,除了我需要将多个域列入白名单 .

    此外,最佳答案还有一个事实,即 OPTIONS 请求不是自动获取的 .

    我将列入白名单的域列为 allowed_origins ,并且根据 origin 标头放置正确的域,因为 Access-Control-Allow-Origin 不允许指定多个域 .

    这就是我最终得到的结果:

    var _ = require('underscore');
    
    function allowCrossDomain(req, res, next) {
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    
      var origin = req.headers.origin;
      if (_.contains(app.get('allowed_origins'), origin)) {
        res.setHeader('Access-Control-Allow-Origin', origin);
      }
    
      if (req.method === 'OPTIONS') {
        res.send(200);
      } else {
        next();
      }
    }
    
    app.configure(function () {
      app.use(express.logger());
      app.use(express.bodyParser());
      app.use(allowCrossDomain);
    });
    
  • 13
    /**
     * Allow cross origin to access our /public directory from any site.
     * Make sure this header option is defined before defining of static path to /public directory
     */
    expressApp.use('/public',function(req, res, next) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        // Request headers you wish to allow
        res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        // Set to true if you need the website to include cookies in the requests sent
        res.setHeader('Access-Control-Allow-Credentials', true);
        // Pass to next layer of middleware
        next();
    });
    
    
    /**
     * Server is about set up. Now track for css/js/images request from the 
     * browser directly. Send static resources from "./public" directory. 
     */
    expressApp.use('/public', express.static(path.join(__dirname, 'public')));
    
    If you want to set Access-Control-Allow-Origin to a specific static directory you can set the following.
    

相关问题