CROS实现跨域访问
生活随笔
收集整理的這篇文章主要介紹了
CROS实现跨域访问
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
今天做了關(guān)于使用CROS做跨域訪問的實驗。
具體的配置如下,
有一個在localhost:80的nginx的簡單html。調(diào)用如下:
$.get('http://localhost:3000/tests').done(function(res){
console.log(res);
}).fail(function(jqXHR){
console.log('failed', jqXHR);
});
有一個在localhost:3000/tests的nodeJs應(yīng)用,簡單的routes如下:
var express = require('express');
var router = express.Router();
/* GET tests. */
router.get('/', function(req, res) {
res.send({'name':'From NodeJs'});
});
module.exports = router;
在本地測試調(diào)用時,無法得到相應(yīng)的數(shù)據(jù),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里面加入準(zhǔn)許訪問的頭部,如下:
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;
為了響應(yīng)更多的CROS請求,需要實現(xiàn)nodeJs中的OPTIONS請求,可以參照stackoverflow中相關(guān)的問題。
總結(jié)
以上是生活随笔為你收集整理的CROS实现跨域访问的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 路由器和电脑的网线怎么接路由器如何连网线
- 下一篇: 怎么创建具有真实纹理的CG场景岩石?