【问题标题】:Ignore http:localhost from ajax url忽略来自 ajax url 的 http:localhost
【发布时间】:2019-05-26 09:11:42
【问题描述】:

我使用 django 频道在我的项目中实现即时消息应用程序。消息框不占用整个屏幕,所以我尝试使用 ajax 来实现它。我面临的问题是,在我的 ajax url 字段中以http://locahost 开头。我不想要这个,因为我使用带有 ws://

的 ASGI 和 django 频道

我尝试在网址前加上“/”

var wsStart = 'ws://';
if (loc.protocol == 'https:'){
    wsStart ='wss://';
 }
var endpoint = wsStart + loc.host;

$.ajax({
  type: 'POST',
  url:"/"+endpoint+"/messages/"+username+"/",
  data: {
  'username': username,
   csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
   },
   success: function (res, status) {
    console.log("RESOPONSE",res);
    },
    error: function (res) {
    console.log(res.status);
   }
  });

我希望 url 是 ws://localhost:8000/messages/

我现在得到的是
http://localhost:8000/ws://localhost:8000/messages/mohitharshan123/

【问题讨论】:

    标签: ajax django django-channels


    【解决方案1】:

    实际上你不能将 WebSocket 与 AJAX 或 CORS 一起使用,这是行不通的。

    【讨论】:

    • 请告诉我任何其他的实现方式
    • 只创建网络套接字我看不出问题出在哪里,即使消息框没有占据整个屏幕
    【解决方案2】:

    问题是您以“/”开头的网址,这意味着您附加其他路径的当前基本网址。首先指定 url ws://localhost,然后附加你想要的。

    【讨论】:

    • 去掉“/”后也一样
    • 添加不带参数的url字符串,硬字符串,必须有效。
    • 对不起..现在它可以工作但现在我遇到了另一个错误 jquery-latest.js:9631 Access to XMLHttpRequest at 'ws://localhost:8000/messages/mohitharshan123/' from origin 'htttp ://localhost:8000' 已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。
    • 在 django 设置中设置允许的主机和 cors。
    • 允许的主机已经设置为 '*' 。对于 cors,我应该安装 django-cors-headers 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多