I'm trying to connect to my websocket from a different domain.
The server is on localhost:8098 and the client is on localhost:8080.
Everytime i try to connect i get a 'Access-Control-Allow-Origin' error, i also added the .setAllowedOrigins("*")
.
Not sure what's missing.
Server
@Configuration
@EnableWebSocketMessageBroker
public class webSocketObjects implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws/Object").setAllowedOrigins("*").withSockJS();
}
Client
<script>
let stompClient=null;
import Stomp from 'stompjs';
import SockJS from 'sockjs-client'
export default {
name: "modal",
props: ['node'],
data() {
return{
bacnetObject: '',
status: "disconnected"
}
},
mounted() {
this.bacnetObject = this.node;
},
methods: {
connect: function(){
const socket = new SockJS('http://localhost:8098/ws/Object');
stompClient = Stomp.over(socket);
stompClient.connect({
}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/user', console.log(String.body))
})
},
disconnect: function () {
stompClient.disconnect();
}
}
}
</script>
Error I am getting:
Access to XMLHttpRequest at 'http://localhost:8098/ws/Object/info?t=1571728150435' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If you're using credentials, *
would not work according to the documentation at MDN. Try to specify the host instead.
For requests without credentials, the literal value "*" can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. Attempting to use the wildcard with credentials will result in an error.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
On the other hand, sometimes depending on your case, you may need to take care of these headers
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: header1, header2 ...
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests