1. Create and run a Nodejs server with a port of: 3000. Exposes an API with a URL of http://localhost:3000/users/. The following is the implementation of the 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. An HTML file to save the following code
Users.html
This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/tools/
3. Using Chrome to open the users.html, open the chrome JavaScript console and see the following error: 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. Change the implementation of the rest API to read as follows:
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;
Note: The access-control-allow-origin is set to ' * ' to indicate that any origin can access the API. This is unsafe in practical applications and requires the designation of specific origin.
5. Run users.html again, the above problem is solved, get the message "respond with a resource".