跨域各种姿势

kuayu.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>测试跨域页面</title>
</head>
<body>
	<h2 id="mainInfo"></h2>
	<input type="button" id="btn" value="点击发送消息">
	<script type="text/javascript">
		var btn = document.getElementById('btn')
		btn.addEventListener('click',()=>{
			var xhr = new XMLHttpRequest();
			xhr.open('get','http://localhost:4000/api/getMsg',true);	
			xhr.send(null);
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					if(xhr.status >=200 && xhr.status<300 || xhr.status==304){
						console.log(xhr.responseText);
					}
				}
			};
		})
	</script>
</body>
</html>

页面中点击按钮会请求localhost:4000服务器的/api/getMsg接口,网站跑在3000端口上,这时候会出现跨域问题

const express = require('express');
const app = express();

app.use(express.static(__dirname));

app.listen(3000,()=>{
	console.log('running...3000');
})
const express = require('express');
const app = express();
const subapp = express();

subapp.get('/getMsg',(req,res)=>{
	console.log(req.query)
	console.log(subapp.mountpath)
	res.send('get message');
});

app.use('/api', subapp)

app.listen(4000,()=>{
	console.log('running...4000');
})
解决办法1  在3000端口采用proxy中间件转发请求到4000,发起请求时候请求3000
xhr.open('get','http://localhost:3000/api/getMsg',true)
const express = require('express');
const app = express();
let { createProxyMiddleware } = require('http-proxy-middleware')

app.use(express.static(__dirname));

app.use('/', createProxyMiddleware({target: 'http://localhost:4000', changeOrigin: true}))

app.listen(3000,()=>{
	console.log('running...3000');
})
解决办法2  在4000服务上通过CORS的方式,加入响应头添加3000的域名进白名单
const express = require('express');
const app = express();
const subapp = express();

let whiteList = ['http://localhost:3000']
app.use(function(req,res,next){
	let origin = req.headers.origin;
	if(whiteList.includes(origin)){
		res.setHeader('Access-Control-Allow-Origin',origin);
	}
	next();
})

subapp.get('/getMsg',(req,res)=>{
	console.log(req.query)
	console.log(subapp.mountpath)
	res.send('get message');
});

app.use('/api', subapp)

app.listen(4000,()=>{
	console.log('running...4000');
})
 解决办法3  通过启用nginx进行反向代理的方式,代理4000,并设置允许跨域,请求地址设置在和3000不同的接口,如3001
xhr.open('get','http://localhost:3001/api/getMsg',true)
server {
        listen       3001;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            proxy_pass   http://localhost:4000;
            index  index.html index.htm;

            add_header 'Access-Control-Allow-Origin' $http_origin;
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain; charset=utf-8';
                add_header 'Content-Length' 0;
                return 204;
            }
        }
.....
}
解决办法4  webpack dev server proxy中进行配置 (略)适合开发时使用
解决办法5  Fiddler中也可以通过插件(willow)配置,还支持其他功能,如接口mock,host配置,proxy代理
j