zoukankan      html  css  js  c++  java
  • CROS实现跨域访问

    今天做了关于使用CROS做跨域访问的实验。

    具体的配置如下,

    有一个在localhost:80的nginx的简单html。调用如下:

    $.get('http://localhost:3000/tests').done(function(res){
        console.log(res);
    }).fail(function(jqXHR){
        console.log('failed', jqXHR);
    });

    有一个在localhost:3000/tests的nodeJs应用,简单的routes如下:

    var express = require('express');
    var router = express.Router();
    
    /* GET tests. */
    router.get('/', function(req, res) {
          res.send({'name':'From NodeJs'});
    });
    
    module.exports = router;

    在本地测试调用时,无法得到相应的数据,chrome会报错如下:

    XMLHttpRequest cannot load http://localhost:3000/tests. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

    正确的方法是在nodeJs里面加入准许访问的头部,如下:

    var express = require('express');
    var router = express.Router();
    
    /* GET tests. */
    router.get('/', function(req, res) {
        res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
          res.send({'name':'From NodeJs'});
    });
    
    module.exports = router;

     为了响应更多的CROS请求,需要实现nodeJs中的OPTIONS请求,可以参照stackoverflow中相关的问题。

  • 相关阅读:
    分页控件(后台拼接html方式)
    精子发生过程
    FSH 促卵泡激素
    LH 黄体生成素
    linux常用命令
    [C#]使用RabbitMQ模拟抽奖系统的例子
    自己写的一个关于Linq to Entity 动态查询的例子
    [C#]记一次解析XML转对象的笔记
    初次使用C#中的yield
    OI回忆录
  • 原文地址:https://www.cnblogs.com/rixin/p/4085701.html
Copyright © 2011-2022 走看看