• REST API之前端跨域访问


    REST API之前端跨域访问

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

     
     
    分类: HTML5JavaScriptNodeJS
  • 相关阅读:
    Centos7
    appium+python常见报错(appium方面)
    python标准库之datetime
    python异常捕获
    python写入文件和读取文件
    python标准库之collections
    python导入类
    python3+robotframework+pycharm安装运行
    python 继承/父类和子类的关系
    python_类
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3781317.html
Copyright © 2020-2023  润新知