这里前端使用的是socket.io,后端是使用java的netty-socketio,这里是通过nginx设置头部来实现跨域,nginx实现cors
需要使用nginx判断method是因为浏览器第一次会发起一个options来检查服务器是否支持跨域访问
代码:
if ($request_method = 'OPTIONS') {
#注意 不需要添加Access-Control-Allow-Origin' 添加以后游览器会设置两个请求头导致报错
# add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}java netty-socketio服务器代码:
Configuration config = new Configuration();
config.setHostname("192.168.3.74");
config.setPort(26840);主要就是配置Hostname跟端口就可以
js 前端代码:
//直接使用域名进行访问不需要写端口
socket = io.connect('ws://xxxxxxx.com/?token='+parmae);
PS:防止连接错误以后一直在重新连接可以使用
socket.on('connect_error', function (error) {
console.log(error);
});
PS2:项目放到服务器的时候需要使用内网ip否则会报Cannot assign requested address异常