zoukankan      html  css  js  c++  java
  • nginx支持webSocket ws请求(解决:WebSocket connection to 'ws://...' failed: Error during WebSocket handshake: Unexpected response code: 200)

    服务端webSocket的java配置文件:

    @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            //允许使用socketJs方式访问,访问点为webSocket,允许跨域
            //在网页上我们就可以通过这个链接
            //ws://127.0.0.1:8585/webSocket来和服务器的WebSocket连接
            registry.addEndpoint("/webSocket").setAllowedOrigins("*");
        }
    

    本地开发时,测试webSocket链接时,直接用的请求为:ws://127.0.0.1:8585/webSocket,其中webSocket为服务端的自己配置的访问点,访问成功,如下图:

    当部署到使用nginx转发的生产环境时,nginx配置:

    location /api/ {
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass http://127.0.0.1:8585;
        ...
    }
    

    当前访问的请求为:ws://域名:2222/api/webSocket,访问失败,如下图:

    异常为:WebSocket connection to 'ws://...' failed: Error during WebSocket handshake: Unexpected response code: 200

    此时,需要nginx配置支持websocket协议ws://,正确的nginx配置为:

    location /api/ {
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass http://127.0.0.1:8585;
        ...
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
    

    访问成功:

  • 相关阅读:
    Ios国际化翻译工具
    软件是什么
    angular2实现图片轮播
    DIV+CSS布局最基本的内容
    angular2中使用jQuery
    如何在Ionic2项目中使用第三方JavaScript库
    Ionic2项目中使用Firebase 3
    Ionic2中ion-tabs输入属性
    The Router路由
    templating(模板)
  • 原文地址:https://www.cnblogs.com/zys-blog/p/12035481.html
Copyright © 2011-2022 走看看