【问题标题】:How to call uWebSockets http routes from front-end with axios?如何使用 axios 从前端调用 uWebSockets http 路由?
【发布时间】:2021-04-01 15:56:34
【问题描述】:

我在我的 nodejs 应用程序上使用 uWebSockets,我正在尝试向 wss 服务器发送一些 http 请求。 我可以通过从浏览器 url 栏访问它们来查看 wss 服务器上 GET 路由的输出,但是当我尝试调用 PUT 、 POST 、 PATCH ……路由时,我没有得到任何输出(例如:没有响应,我想路线未到达)。

我的 uWebSockets.js 配置如下代码 sn -p :

const uWS = require('uWebSockets.js');
const SOCKET_PORT = 3023;

const websockets = uWS.App()

/* I tried to put these routes before and after .ws() , still no response */
.put('/route1', (req, res) => {
     console.log('/route1');
})
.patch('/route2', (req, res) => {
     console.log('/route2');
 })
.post('/route3', (req, res) => {
     console.log('/route3');
})
.delete('/route4', (req, res) => {
     console.log('/route4');
})

/* Tried with '' , '*' , '/*' but none of the attempts succeeed */
.ws('', {
     compression: uWS.SHARED_COMPRESSOR,
     idleTimeout: 30,
     maxBackpressure: 1024,
     maxPayloadLength: 512,
     open:ws=> ws.subscribe('all')
});


websockets.listen(SOCKET_PORT, (listenSocket) => {
    if (listenSocket) 
        console.log('Listening to port ' + SOCKET_PORT);
});

从前端,我尝试像这样发送请求:

    let header = { "Access-Control-Allow-Origin" : "*" , "Content-Type" : "application/json" };
    header.key= "test_key";
    await axios({
        method : "PUT",
        url : "wss://subdomain.domain.xyz/route1",
        data : { "val1" : "test" , "val2" : 5 },
        headers : header
    })
    .then(function(response){
        serverResponse = response.data;
    })
    .catch(function(err){
        serverResponse = err.response.data;
    });

我做的 websockets 请求错了吗?

我使用的是 18.04 uWebSockets.js 版本。

【问题讨论】:

  • 您正在尝试使用 HTTP 客户端库来连接 websockets,它不是为 axios 设计的。如果您坚持使用 websockets 协议,则必须使用其他库并更改逻辑
  • 确实,我试过用axios调用websocket http路由。究竟如何更改我的逻辑以及要使用的其他库?

标签: javascript node.js websocket axios uwebsockets


【解决方案1】:

在使用 GET、POST、PATCH、PUT、DELETE 等 HTTP 方法时,您应该使用 http/https 而不是 ws/wss 进行连接。

【讨论】:

  • +1 此外,uWebsockets.js 既是 HTTP 又是 WebSockets 服务器,因此使用简单的 HTTP 协议访问这些路由应该不是问题。
  • 是的,你是对的,同时我已经发现这是问题的一部分。但是,通过 HTTP 访问路由仅适用于 GET 路由,其他路由由于某种原因无法访问......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
  • 2021-03-02
  • 2021-02-18
  • 2021-03-01
  • 2018-07-13
  • 1970-01-01
相关资源
最近更新 更多