最近在学习原生js的XMLHTTPRequest与跨域资源共享(CORS),想着用js简单的实现下post跨域请求,代码贴出来以供其他初学者参考.
这是客户端代码
<html>
<body>
<script>
var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
// 前端设置是否带cookie
xhr.withCredentials = true;
xhr.open('post', 'http://10.68.11.230:8081/login?xixi=xixi', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
</script>
</body>
</html>
后端nodejs代码 server.js
var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request', function(req, res) {
var postData = '';
// 数据块接收中
req.addListener('data', function(chunk) {
postData += chunk;
});
// 数据接收完毕
req.addListener('end', function() {
postData = qs.parse(postData);
// 跨域后台设置
res.writeHead(200, {
'Access-Control-Allow-Credentials': 'true', // 后端允许发送Cookie
'Access-Control-Allow-Origin': 'http://localhost:4200', // 允许访问的域(协议+域名+端口)
/*
* 此处设置的cookie还是domain2的而非domain1,因为后端也不能跨域写cookie(nginx反向代理可以实现),
* 但只要domain2中写入一次cookie认证,后面的跨域接口都能从domain2中获取cookie,从而实现所有的接口都能跨域访问
*/
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly的作用是让js无法读取cookie
});
res.write(JSON.stringify(postData));
res.end();
});
});
server.listen('8081');
console.log('Server is running at port 8081...');
我把html和服务端js文件放在了单独的文件夹,运行node server.js
即可运行服务端代码.
通过http-server(没有的话npm install http-server -g
)安装一个,在客户端html代码存放的文件夹运行
http-server -p <自定义端口号>
即可让客户端代码跑起来
打开chrome调试工具即可看到客户端发送的跨域请求.