1、cors 后台解决跨域
res.header("Access-Control-Allow-Origin", "*"); // 允许所有路径跨域
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
eg:
$.get('http://localhost:3000/all',{
name:'xiaohua',
age:18
},function(data){
console.log(data);
})
var express=require('express');
var app=express();
// 解决跨域问题
app.all("/*", function(req, res, next) {
// 跨域处理
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next(); // 执行下一个路由
})
app.get('/all',function(req,res){
console.log(req.url);
res.send(req.query);
})
app.listen(3000,function(){
console.log(3000);
})
2、jsonp:res.jsonp()
eg:
$.ajax({
url:'http://localhost:3002/nan',
dataType:'jsonp',
data:{
uname:'xiaohua',
uage:18
},
success:function(data){
console.log(data);
}
})
var express=require('express');
var app=express();
app.get('/nan',function(req,res){
res.jsonp({
number:100,
name:req.query.uname,
age:req.query.uage
})
})
app.listen(3002,function(){
console.log(3002);
})
3、代理
(1)依赖一个插件, http-proxy-middleware;
(2)配置插件:var apiproxy =
proxy("/", {
target: "http://tingapi.ting.baidu.com",
changeOrigin: true
})
(3)使用app.use(apiproxy);
eg:
var express=require('express');
var httpProxy = require('http-proxy-middleware');
var app=express();
app.all("/*", function(req, res, next) {
// 跨域处理
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next(); // 执行下一个路由
})
// 配置代理
var apiproxy = httpProxy("/music", {
target: "http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0",
changeOrigin: true
})
app.use(apiproxy);
app.listen(3000,function(){
console.log('服务器运行在3000端口');
})