node-tutorial
                                
                                 node-tutorial copied to clipboard
                                
                                    node-tutorial copied to clipboard
                            
                            
                            
                        node跨域
后端
var http=require('http');
var querystring=require('querystring');
http.createServer(function(req,res){
  var postData='';
  req.setEncoding('utf8');
  req.on('data',function(chunk){
    postData+=chunk;
  });
  req.on('end',function(){
    res.end(postData+"hehe");
  });
}).listen(3000);
console.log("服务启动。。。")
前端
$(function(){
  $("#test").click(function(){
    $.ajax({
      'url':'http://localhost:3000',
      'method':'POST',
      'data':{},
      'success':function(data){
        console.log(data);
      }
    });
  });
})
正常情况会发生跨域
XMLHttpRequest cannot load http://localhost:3000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
这测试环境下我们可以这样解决 在createServer方法里面第一行设置
res.setHeader('Access-Control-Allow-Origin', '*');
*号代表允许任何与的请求,当然实际生产环境不可能这么做 你可以通过报错提示找到被拒绝的域然后设置
res.setHeader('Access-Control-Allow-Origin', '域名');
比如我在HBulider里面打开html文件是这样设置
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8020');