CORS 跨域 node |XMLHttpRequest 跨域提交数据 node

node服务端

app.post('/getdata',function(req,res,next){
  req.setEncoding('utf8');
  res.setHeader('Access-Control-Allow-Origin','*')
  req.on('data',function(str){
    var json = JSON.parse(str||"{}") ;
   console.log(json) 
  })
  res.end('already get data')
}) 

script前台页面

var req = new XMLHttpRequest();

if ("withCredentials" in req) { 
	// 此时即支持CORS的情况 
	// 检查XMLHttpRequest对象是否有“withCredentials”属性 
	// “withCredentials”仅存在于XMLHTTPRequest level 2对象里 
} else { 
	// 否则检查是否支持XDomainRequest 
	// XDomainRequest仅存在于IE中,是IE用于支持CORS请求的方式 
	req = new XDomainRequest(); 
}

req.open('POST',"http://localhost:3000/getdata");
// req.setRequestHeader('Content-Type','text/plain')
//  req.onreadystatechange = function(){
//      if(req.readyState == 4 && req.status == 200){
		// //var tt = req.getResponseHeader("Content-Type")
//          alert(req.responseText);
//      }	
//  }
req.onload = function(){
	alert(req.responseText);
}
req.send('this is data')
原文地址:https://www.cnblogs.com/liujinyu/p/5181084.html