美文网首页
nodejs 跨域CORS

nodejs 跨域CORS

作者: 铁木真丫丫丫 | 来源:发表于2017-06-09 20:49 被阅读504次

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。

(1)Access-Control-Allow-Origin

该字段是必须的。它的值要么是请求时Origin字段的值,要么是一个*,表示接受任意域名的请求。

(2)Access-Control-Request-Method

该字段是必须的,用来列出浏览器的CORS请求会用到哪些HTTP方法,上例是PUT。

(3)Access-Control-Expose-Headers

该字段可选。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。上面的例子指定,getResponseHeader('FooBar')可以返回FooBar字段的值。

启动nodejs web应用的app.js
var express = require("express");  
var http = require("http");  
var app = express();  
  
  
var router = express.Router();  
var testRouter =  require('./routes/test/test');  
  
  
app.use('/test', testRouter);  
http.createServer(app).listen(3000);  
处理具体api的控制器 test.js
var express = require('express');  
var router = express.Router();  
  
/* GET home page. */  
router.get('/', function(req, res, next) {  
  res.render('index', { name: 'Express 路由1' });  
});  
  
/* GET home page. */  
router.get('/cors', function(req, res, next) {  
  res.render('test/index', { name: 'Express 路由1' });  
});  
  
/* GET home page. */  
router.get('/getData', function(req, res, next) {  
  //设置允许跨域请求  
  var reqOrigin = req.header("origin");  
  
  if(reqOrigin !=undefined && reqOrigin.indexOf("http://localhost:3000") > -1){  
  //设置允许 http://localhost:3000 这个域响应  
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");  
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");  
  }  
  res.json(200, {name:"张三1",age:40});  
  
});  
  
module.exports = router;  
模板页面,发送ajax跨域请求
<!DOCTYPE html>  
<html lang="zh-CN">  
<head>  
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  
    <script src="../public/js/jquery.min.js"></script>  
    <script src="../public/js/hb_common.js"></script>  
    <link rel="stylesheet" href="../public/css/bootstrap.min.css">  
    <link rel="stylesheet" href="../public/css/hb_wap.css">  
    <title>test</title>  
</head>  
  
<body >  
  
<button class="btn btn-primary" id="btn" onclick="corsGetData()">cors跨域获取数据</button>  
<br>  
  
<button class="btn btn-primary" id="btn4" onclick="getData()">不跨域获取数据</button>  
<br>  
  
  
</body>  
<script>  
    function getData(){  
        $.ajax({  
            url: "http://localhost:3000/test/getData",  
            type:"GET",  
            cache: false,  
            success: function(html){  
                alert(html);  
                $("#results").append(html);  
            }  
        })  
  
    }  
  
    function corsGetData(){  
        $.ajax({  
            url: "http://www.huangbiao.com:3000/test/getData",  
            type:"GET",  
            cache: false,  
            success: function(html){  
                alert(html);  
                $("#results").append(html);  
            }  
        })  
  
    }  
</script>  
</html>  

相关文章

网友评论

      本文标题:nodejs 跨域CORS

      本文链接:https://www.haomeiwen.com/subject/krwfqxtx.html