關鍵字:跨域訪問,cross-origin, NodeJS, REST API, JavaScript, Access-Control-Allow-Origin
1.新建並運行一個 NodeJS的server,端口為:3000。暴露一個API, URL為http://localhost:3000/users/。以下為該API的實現:
users.js
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文件
users.html
<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。
5.再次運行users.html,以上問題解決,得到消息“respond with a resource”。
參考資料:http://www.w3.org/TR/2013/CR-cors-20130129/