对XMLHttpRequest的访问已被CORS政策阻止:请求的资源上没有“ Access-Control-Allow-Origin”标头

问题描述

我有一个React应用程序,试图连接到STOMP websocket,当我尝试连接时,它给了我这个错误:

当我使用代理时: 从CORS策略阻止从源“ http:// localhost:3000”访问“ XXX”处的XMLHttpRequest:响应中“ Access-Control-Allow-Origin”标头的值不得为通配符“ *”当请求的凭据模式为“包含”时。 XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。

当我不使用代理时: CORS策略已阻止从来源“ http:// localhost:3000”访问“ xxx”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。

技术:Stomp,SockJS 库:react-stomp

代码:

import SockJsClient from 'react-stomp'
import { Button } from 'antd'

const Websocket = () => {
  const [clientRef,setClientRef] = useState(false)
  console.log(clientRef)
  const sendMessage = (msg) => {
    if (clientRef) {
      clientRef.sendMessage('/app/hello',msg)
    }
  }

  return (
    <div>
      <SockJsClient
        url="xxx"
        topics={['/topic/greeting']}
        onMessage={(msg) => {
          console.log(msg)
        }}
        ref={(client) => {
          setClientRef(client)
        }}
      />

      <Button
        onClick={() => {
          sendMessage({ name: 'Ricardo' })
        }}
        type="submit"
      >
        Greeting
      </Button>
    </div>
  )
}

export default Websocket

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...