REST API before-end cross domain access

Source: Internet
Author: User
Tags require resource

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".

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.