JSONP跨域获取数据
1.前端代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="get" >异步获取数据</button>
<script src="js/des/jquery-2.2.4.js"></script>
<script>
var log=function (obj) {
console.log(obj);
}
var get=document.getElementById('get');
get.addEventListener('click',function () {
$.getJSON('http://192.168.0.250:9000/bannerUrl?callback=?',function (data) {
log('result data:'+data.name);
});
},false);
</script>
</body>
</html>
2.nodejs代码
var express = require('express');
var router = express.Router();
var urllib=require('url');
//获取banner url
router.get('/bannerUrl',function (req,res,next) {
var data = {'name': 'jifeng', 'company': 'taobao'};
var params=urllib.parse(req.url,true);
//console.log('请求1:'+params);
if (params.query && params.query.callback) {
//console.log('请求2:'+params.query);
var str = params.query.callback + '(' + JSON.stringify(data) + ')';//jsonp
res.send(str);
} else {
res.send(JSON.stringify(data));//普通的json
}
});
POST跨域获取数据
1.前端代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="get" >异步获取数据</button>
<script>
var log=function (obj) {
console.log(obj);
}
var get=document.getElementById('get');
get.addEventListener('click',function () {
var xhr=new XMLHttpRequest();
xhr.onload=function () {
log(this.responseText);
}
xhr.open('post','http://192.168.0.250:9000/bannerUrl',true);
xhr.send();
},false);
</script>
</body>
</html>
2.nodejs代码:
//获取banner url
router.post('/bannerUrl',function (req,res,next) {
res.setHeader('Access-Control-Allow-Origin','http://192.168.0.250:3001');
res.send({name:'wzh'});
});
Nodejs解决所有跨域请求
1.nodejs code:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});