问题
用koa2作为服务端,在解决跨域问题时需要获取客户端请求的origin字段前端使用ajax访问服务端接口,客户端请求的request中origin为null
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 module .exports = async function (ctx, next ) { const origin = URL .parse (ctx.get ('origin' ) || ctx.get ('referer' ) || '' ); if (origin.protocol && origin.host ) { ctx.set ('Access-Control-Allow-Origin' , `${origin.protocol} //${origin.host} ` ); ctx.set ('Access-Control-Allow-Methods' , 'POST, GET, OPTIONS, DELETE, PUT' ); ctx.set ('Access-Control-Allow-Headers' , 'X-Requested-With, User-Agent, Referer, Content-Type, Cache-Control,accesstoken' ); ctx.set ('Access-Control-Max-Age' , '86400' ); ctx.set ('Access-Control-Allow-Credentials' , 'true' ); } if (ctx.method !== 'OPTIONS' ) { await next (); } else { ctx.body = '' ; ctx.status = 204 ; } }
原因
客户端请求服务端接口是在本地电脑环境(非服务器环境),然而origin字段记录的是我发起http请求的域名URL,由于我是在本地进行访问的,肯定也就不存在域名URL了。
解决
全局安装http-server (搭建服务器环境)
1 npm install http-server -g
1 2 3 4 5 6 D :\uidq2225\Desktop \test>http-serverStarting up http-server, serving ./Available on : http : http : Hit CTRL -C to stop the server