关键字:跨域访问,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/