[node.js] ‘액세스 제어 허용 출처’없음-노드 / 아파치 포트 문제

Node / Express를 사용하여 작은 API를 만들고 Angularjs를 사용하여 데이터를 가져 오려고했지만 html 페이지가 localhost : 8888에서 아파치로 실행 중이고 노드 API가 포트 3000에서 수신 대기 중이므로 No ‘Access-Control- 허용-원본. node-http-proxyApache를 사용 하고 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.module('contractorsApp', [])
.controller('ContractorsCtrl', function($scope, $http,$routeParams) {

   $http.get('localhost:3000').then(function(response) {
       var data = response.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>



답변

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();
});

희망이 도움이됩니다!


답변

더 짧은 것을 선호하는 경우 받아 들일 수있는 대답은 괜찮습니다 .Express.js에 사용할 수있는 cors 라는 플러그인을 사용할 수 있습니다

이 특별한 경우에 사용하는 것이 간단합니다.

var cors = require('cors');

// use it before all route definitions
app.use(cors({origin: 'http://localhost:8888'}));


답변

다른 방법은 단순히 헤더를 경로에 추가하는 것입니다.

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:)');
});


답변

상단의 대답은 내가 허용 된 사이트 목록 개 이상의 도메인에 필요한 것을 제외하고, 나를 위해 벌금을했다.

또한 최고 답변은 OPTIONS요청이 미들웨어에 의해 처리되지 않고 자동으로 얻지 못한다 는 사실로 인해 어려움을 겪 습니다.

allowed_originsExpress 구성에서와 같이 화이트리스트 도메인을 저장 하고 둘 이상의 도메인을 지정할 수 없으므로 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);
});


답변

응답 코드는 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();
});


답변

프로젝트에 cors 종속성을 설치하십시오.

npm i --save cors

서버 구성 파일에 다음을 추가하십시오.

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

2.8.4 cors 버전으로 작동합니다.


답변

이것은 나를 위해 일했습니다.

app.get('/', function (req, res) {

    res.header("Access-Control-Allow-Origin", "*");
    res.send('hello world')
})

필요에 따라 *를 변경할 수 있습니다. 이것이 도움이되기를 바랍니다.