如何添加头到套接字响应?

时间:2018-09-20 10:17:59

标签: spring spring-boot websocket sockjs

我正在尝试使用套接字制作一个通知系统。

我的代码:

WebSocketConfiguration.java

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfiguration extends 
    AbstractWebSocketMessageBrokerConfigurer {

        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/handler")
                .setAllowedOrigins("http://city.localhost")
                .withSockJS();
        }

        @Override
        public void configureMessageBroker(MessageBrokerRegistry brokerRegistry) {
            brokerRegistry.setApplicationDestinationPrefixes("/app");
            brokerRegistry.enableSimpleBroker("/topic", "/queue");
        }

    }

NotificationController.java

@RestController
@RequestMapping("/api")
public class NotificationController {

    @Autowired
    private SimpMessagingTemplate template;

    @Autowired
    private NotificationService notificationService;

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/notification", method = RequestMethod.GET)
    public List<Notification> sendNotification() {
        List<Notification> notifications = notificationService.findAll();

        //Here I'm trying to add a header, but it does not work
        Map<String, Object> headers = new HashMap<>();
        headers.put("Access-Control-Allow-Origin", "http://city.localhost");

        template.convertAndSend("/topic/all", notifications, headers);
        return notifications;
    }

}

notification.js

class Notification extends React.Component {
    constructor(props){
    super(props);
    this.state = {
      ignore: true,
      title: ''
    };
  }
    render() {
      const wsSourceUrl = "http://localhost/handler";

      return (
        <div>
            <SockJsClient url={ wsSourceUrl } topics={["/topic/all"]}
                      onMessage={ this.onMessageReceive }
                      onConnect={ () => { console.log("connected") } }
                      onDisconnect={ () => { console.log("connected") } }
                      debug={ false }/>
      </div>
    )
  }
}

现在我有问题:

enter image description here

据我了解,问题是在答案Access-Control-Allow-Origin为“ *”时,我需要http://city.localhost/,因此无法在响应中放入这样的标题。 我可能是错的,其中可能没有问题,我将很乐意提供帮助

0 个答案:

没有答案