Nodejsクロスドメイン解決案


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、json:res.jsop()
  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 approxy=                                proxy("/",{                                    タージ:"http://tingapi.ting.baidu.com「                                    change Origin:true                                })
  (3)app.useを使用する;
  eg:
    
    
       $.get('http://localhost:3000/music',function(data){
           console.log(data);
       })
    
    
 
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  ');
})