Ajax 在快速中间件中访问第三方服务器会导致 500 错误

ajax get to 3rd party server within express middleware results in 500 error

本文关键字:服务器 错误 第三方 访问 中间件 Ajax      更新时间:2023-09-26

我需要从HTML5 Web应用程序通过IP访问多个设备。

我解决在客户端无法完成这一切的跨域问题的方法是在 Express 中间件中"烹饪"来自客户端的请求。路由从客户端接收获取或发布,然后执行获取或发布到由客户端的有效负载标识的第三方设备。

我正在使用代码从设备获取信息。当我直接从我为测试目的而制作的客户端中的文件运行它时,它工作得很好。直接从文件运行避免了 CORS 困难,因为我想客户端也是服务器。

当我从快速路由中运行相同的代码时,出现 500 错误。

我是在尝试做不可能的事情吗?我只进入节点、快递等大约一周,所以希望这是愚蠢且易于解决的问题。 事实上,我无法找到任何其他类似的问题,这表明有一种正确的方法可以实现我需要的东西。

// post to find a camera
router.post('/find', function(req, res) {
    var url = 'http://' + req.body.addr + '/cgi-bin/aw_cam?cmd=QID&res=1';
    console.log(url);
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'html',
        success: function (result) {
        console.log('success: ' + result);
        res.send(result);
        },
        error: function (xhr, textStatus, err) {
            console.log('error: ' + textStatus);
        }
    });
});

以下是记录到服务器控制台的内容:

http://192.168.0.10/cgi-bin/aw_cam?cmd=QID&res=1
POST /cameras/find 500 126.593 ms - 1656

提前感谢!

好的,

我找到了如何做到这一点。诀窍是使用Node的内置http消息传递功能。我在这里找到了一篇关于如何做到这一点的好文章

下面的代码完全符合我在自定义路由中间件中的要求。我想我刚刚了解到我只能在客户端按照我想要的方式使用 AJAX。

这让我可以将设备控制协议的更毛茸茸的细节抽象到服务器中,让我的客户端应用使用 JSON/AJAX 模型与它们进行交互。成功!

var http = require('http');
// post to find a camera
router.post('/find', function(req, res) {
    var url = 'http://' + req.body.addr + '/cgi-bin/aw_cam?cmd=QID&res=1';
    console.log(url);
    http.get(url, (response) => {
        console.log(`Got response: ${response.statusCode}`);
        var body = '';
        response.on ('data', function(d) {
            body += d;
        });
        response.on ('end', function () {
            console.log('received: ' + body);
            var reply = {};
            if (body.indexOf('OID:') == 0) {
                reply.msg = body.slice(4);
                reply.ok = true;
            } else {
                reply.msg = body;
                reply.ok = false;
            }
            res.send(reply);
        });
        // consume response body
        response.resume();
    }).on('error', (e) => {
        console.log(`Got error: ${e.message}`);
    });
});