REST API以前端跨域訪問

關鍵字:跨域訪問,cross-origin, NodeJS, REST API, JavaScript, Access-Control-Allow-Originjavascript

 

1.新建並運行一個 NodeJS的server,端口爲:3000。暴露一個API, URL爲http://localhost:3000/users/。如下爲該API的實現:html

users.jsjava

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res) {
  res.send('respond with a resource');
});

module.exports = router;

2.將如下代碼保存的一個html文件web

users.htmlexpress

<html>

<head></head>

<body>
<script type="text/javascript">
var request = new XMLHttpRequest();
var url = "http://localhost:3000/users";
request.open('GET', url, true);
request.onreadystatechange = handler;
request.send(); 

function handler(evtXHR)
{
    if (request.readyState == 4)
    {
        if (request.status == 200)
        {
            var response = request.response;
            alert(response);
            
        }
        else
            alert("Request Errors Occured");
    }
}
</script>
</body>

</html>

3.用Chrome打開users.html, 打開Chrome的JavaScript的控制檯,看到如下錯誤:XMLHttpRequest cannot load http://localhost:3000/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.跨域

4.將REST API的實現改成以下:安全

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.send('respond with a resource');
});

module.exports = router;

注:把Access-Control-Allow-Origin設置爲‘*’,表示任意origin能夠訪問該API. 在實際應用中這樣是不安全的,須要指定具體的origin。cors

5.再次運行users.html,以上問題解決,獲得消息「respond with a resource」。ui

 

參考資料:http://www.w3.org/TR/2013/CR-cors-20130129/url

相關文章
相關標籤/搜索