解决Node.Js跨域问题

跨域:用个人理解的一种现象来说,个人电脑相当于一个站点,本地的html文档中写了一段js代码,其url地址请求www.baidu.com(或者本地服务器地址),就是一种跨域现象。

抛出异常:  Origin 'null' is therefore not allowed access.

解决:对于NodeJs来说,在js服务器页面加入代码:

res.setHeader("Access-Control-Allow-Origin", "*"); 
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.setHeader("X-Powered-By",' 3.2.1');
res.setHeader("Content-Type", "text/html"); 


完整实例:

node.js服务器代码:

var http=require("http")
var fs = require('fs')
var server=http.createServer();
server.on('request',function(req,res){

res.setHeader("Access-Control-Allow-Origin", "*"); 
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.setHeader("X-Powered-By",' 3.2.1');
res.setHeader("Content-Type", "text/html"); 

    if(req.url === "/login"){
          fs.readFile('./login.html','utf-8',function(err,data){
        	if(err){
        		console.log(err)
        	}
        	res.end(data)         
        }) 

    }
    
})


server.listen(1337,"localhost",function(){
    console.log("开始监听...");
});
基于ajax的服务器请求:




	
	Document
	
    


	
	
js代码:

$(function(){
  $('input').load('http://localhost:1337/login',function(response,status,xhr){
	  $('#box').html(response);
  });
});

本地主机被请求的html页面:




	Document


	

欢迎登陆




------------------------

返回json数据:

var http=require("http")
var fs = require('fs')
var url = require('url')
var server=http.createServer();
server.on('request',function(req,res){

res.setHeader("Access-Control-Allow-Origin", "*"); 
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.setHeader("X-Powered-By",' 3.2.1');
res.setHeader("Content-Type", "application/json"); 
    
     var result = url.parse(req.url,true).query
     console.log(result.id)
    if(req.url === "/login"){
          fs.readFile('./login.html','utf-8',function(err,data){
        	if(err){
        		console.log(err)
        	}
        	res.end('{"id":12,"user":"zhangsan"}')    //json对象的属性需要加""     
        }) 

    }
    
})


server.listen(1337,"localhost",function(){
    console.log("开始监听...");
});







你可能感兴趣的:(NodeJs)