2016-06-24 2 views
0

, 나는 http://localhost:3000/api/delivered에 JSON 데이터를 게시하려고 응용 프로그램을 express.js. HTML 파일 -크로스 도메인 jQuery를 AJAX 포스트 JSON 데이터를 내 Node.js를에서

<html> 
<body> 
<input type="submit" value="submit" id="delivered"/> 
</body> 

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" </script> 
<script type="text/javascript"> 

$('#delivered').on('click', function() { 
     var id = {"_id": "123"}; 

     $.ajax({ 
      type: 'POST', 
      url: 'http://localhost:3000/api/delivered', 
      contentType: 'application/json', 
      data : JSON.stringify(id), 
      dataType: "json", 
      success: function() { 
       console.log('Delivered'); 
      }, 
      error: function() { 
       alert('Error occured while entering'); 
      } 
     }); 

    }); 

내가 http://localhost:3000/api/delivered를로드 할 수 없습니다 에러 -

XMLHttpRequest의를 얻고있다. 프리 플라이트 요청에 대한 응답이 액세스 제어 검사를 통과하지 못합니다. 'Access-Control-Allow-Origin'헤더가 요청 된 자원에 없습니다. 따라서 원본 'null'은 액세스가 허용되지 않습니다. 당신의 NodeJS에 다음 미들웨어를 추가

+0

당신이 CORS를 지원하지 않습니다 전화하는거야 도메인, '왜 이렇게 [동일 출처 정책] (http://en.wikipedia.org/wiki/Same-origin_policy)에 의해 차단됩니다. 도메인을 제어한다고 가정하면 서버에서 CORS 헤더를 활성화해야합니다. 서버를 제어 할 수없는 경우 중복으로 표시된 질문에 나열된 대안 중 하나를 사용해야합니다. –

+0

몇 가지 솔루션을 확인했지만 제대로 작동하지 않았습니다. 그래서 내 특정 코드를 게시했습니다. 감사합니다. 중복으로 표시된 질문을 확인해 보겠습니다. –

답변

0

시도/특급 응용 프로그램

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

또 다른 방법은 다음과 같습니다 :

var cors = require('cors'); 

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

내 중앙'app.js'와'api.js (라우팅 정의 용)'는 다음과 같습니다. http://pastebin.com/ixHSQ5Bv http://pastebin.com/jRVRPvCS 변경 사항을 동일하게 변경했습니다. 오류. 제가 제대로했는지 확인해 주실 수 있습니까? 매우 도움이 될 것입니다. –

관련 문제