我有一个在localhost:8080上运行的SpringBoot服务器 和本地主机上的npm(提供React应用程序):3000
每当我尝试建立一个到spring的websocket连接时,这会显示在浏览器的控制台上(Firefox Nightly):
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost:8080/ws/info?t=1522629329791.
(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match
‘http://localhost:8080/ws/info’).
我已经创建了一个WebSocketMessageBrokerConfigurer
课程,并尝试setAllowedOrigins
宽度为null和http://localhost:3000
(以及127.0.0.1
):
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("http://localhost:3000")
.withSockJS();
}
REST请求工作正常,我甚至在一个简单的节点脚本中连接到websocket,但在浏览器中我没有运气。这就是我在浏览器中连接的方式(与脚本相同):
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';
...
let ws = new SockJS('http://localhost:8080/ws/');
let client = Stomp.over(ws);
client.connect({'some-header': 'some-data'}, (success) => {
//client.subscribe(...
}, (error) => {
console.log(error)
})
有人能帮助我吗?提前谢谢。
答案 0 :(得分:0)
尝试.setAllowedOrigins("*")
- 允许所有ORIGIN
s:
/**
* Configure allowed {@code Origin} header values. This check is mostly designed for
* browser clients. There is nothing preventing other types of client to modify the
* {@code Origin} header value.
*
* <p>When SockJS is enabled and origins are restricted, transport types that do not
* allow to check request origin (JSONP and Iframe based transports) are disabled.
* As a consequence, IE 6 to 9 are not supported when origins are restricted.
*
* <p>Each provided allowed origin must start by "http://", "https://" or be "*"
* (means that all origins are allowed). By default, only same origin requests are
* allowed (empty list).
*
* @since 4.1.2
* @see <a href="https://tools.ietf.org/html/rfc6454">RFC 6454: The Web Origin Concept</a>
* @see <a href="https://github.com/sockjs/sockjs-client#supported-transports-by-browser-html-served-from-http-or-https">SockJS supported transports by browser</a>
*/
StompWebSocketEndpointRegistration setAllowedOrigins(String... origins);
答案 1 :(得分:0)
我没有设法用spring解决这个问题(在服务器端),但我找到了一个解决方法。通过使用webpack(我使用create-react-app,默认使用webpack),可以简单地将请求代理到“正确”的地址:
"proxy": "http://localhost:8080/"
在package.json
上。在开发应用程序时解决问题。但在生产中对你没有任何帮助。但是由于webapp由tomcat提供服务(编译后的版本(即npm run build
的结果放在服务器上(src/main/resources/static
),通过一些配置它可以正常工作。