0

我正在做一个 ESP32 项目。我的目标之一是使用 javascript fetch 或 XMLHttpRequest() 从网站与 ESP32 通信。

ESP32 连接到我的本地网络,我正在使用 esp32_https_server 库。它使用浏览器指示为有效的自签名证书(但由于自签名证书而发出警告“连接不受保护”)。该网站具有 CA 证书并且是安全的。

在测试中,esp32 通过 USB 连接到我的电脑,理想情况下我希望它独立。

我遇到的问题是我似乎无法连接到 esp32。我不断收到状态码 499 错误。

我的问题是:

1) 我如何从安全网站成功连接到 esp32 服务器以从 esp32 获取数据?

2) 当 esp32 没有通过 USB 电缆连接到我的电脑时,我该怎么做?

请在下面查看有关 esp32 设置和响应的更多信息。

这是 esp32 代码:

ResourceNode *nodeRoot = new ResourceNode("/", "GET", [](HTTPRequest *req, HTTPResponse *res) {
    ResourceParameters *params = req->getParams();
    std::string action = params->getRequestParameter("action");

    String aksie = action.c_str();

    Serial.println("Aksie: " + aksie);

    if (aksie != "upload_data" && aksie != "upload_current_temp")
    {
        // this should be home page displayed
        // Set the response status
        res->setStatusCode(200);
        res->setStatusText("success");
        res->println("Secure Hello World!!!");
    }
    else
    {
        // either uploads..
        processParams(aksie, res);
    }
});

secureServer->registerNode(nodeRoot);

这是处理“upload_current_temp”请求的代码:

if (action == "upload_current_temp")
{
    // get random temperature
    int currentTemp = random(0, 9);
    String temp = String(currentTemp);

    Serial.println("upload current temperature");
    Serial.println("uploadCurrentTemp: " + temp);
    std::string tem = temp.c_str();
    // Set the response status
    res->setStatusCode(200);
    res->setStatusText("success current temperature");

    StaticJsonDocument<200> doc;
    doc["temperature"] = temp;
    // Produce a minified JSON document
    String output;
    serializeJson(doc, output);
    Serial.println("curent temp json output: " + output);

    deserializeJson(doc, output);

    // Set the content type of the response
    res->setHeader("Content-Type", "application/json");
    res->setHeader("Access-Control-Allow-Origin", "*");
    res->setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");

    // As HTTPResponse implements the Print interface, this works fine. Just remember
    // to use *, as we only have a pointer to the HTTPResponse here:
    serializeJson(doc, *res);
}

而且在 setUp() 我有这一行:

secureServer->setDefaultHeader("Access-Control-Allow-Origin", "*"); //replace * with actual address

使用时:

 const xhr = new XMLHttpRequest();
    const url = 'https://192.168.0.102/?action=upload_current_temp';

    xhr.open('GET', url);

    xhr.responseType = 'text';
    xhr.onload = function () {

        const data = xhr.response;
        console.log(data);

        if (this.readyState == 4 && this.status == 200) {
            var obj = JSON.parse(this.responseText);
            console.log("getCurTemp(), responseText: " + JSON.stringify(this.responseText, null, 2));
            currentTemperature = obj.temperature;
            console.log("current temperature: " + currentTemperature);
            document.getElementById('currentTemp').innerHTML = currentTemperature;
        }
    };
    xhr.send();

我得到这些错误(在歌剧中):

499(请求已被杀毒软件禁止)

已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

在铬:

已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

使用这些标题(歌剧):

请求网址:https ://192.168.0.102/?action=upload_current_temp 请求方法:GET

状态码:499 请求已被杀毒软件禁止

远程地址:192.168.0.102:443

推荐人政策:降级时无推荐人

缓存控制:无存储,无缓存,必须重新验证,max-age=0

连接:关闭

内容长度:52266

内容类型:文本/html;字符集=utf-8

过期时间:1999 年 12 月 4 日星期一 21:29:02 GMT

Pragma:无缓存

接受:/

接受编码:gzip、deflate、br

接受语言:en-US,en;q=0.9

连接:保持活动

主机:192.168.0.102

来源:https ://istimuli.co.uk

推荐人:https ://istimuli.co.uk/?code=66b72f8e-400c-4adb-ad42-f4efec391d06

Sec-Fetch-Dest:空

Sec-Fetch-Mode: cors

Sec-Fetch-Site:跨站点

用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 OPR/67.0.3575.79

行动:upload_current_temp

使用时:

var url = "https://192.168.0.102/?action=upload_current_temp";

    var request = new Request(url, {
        method: 'GET',
        mode: 'cors', // no-cors, *cors, same-origin
        headers: {
            'Content-Type': 'application/json'
        }
    });

    fetch(request).then(function (response) {
        // Convert to JSON
        return response.json();
    }).then(function (data) {
        console.log("temp: " + JSON.stringify(data));
        return data;
    }).catch(function (error) {
        console.log('Request failed', error)
        return 000;
    });

我在歌剧中得到这些错误:

499(请求已被杀毒软件禁止)

已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

在 chrome 中:已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

这些是标题(歌剧):

1 个请求

已传输 51.3 KB

51.0 KB 资源

请求网址:https ://192.168.0.102/?action=upload_current_temp

请求方法:选项

状态码:499 请求已被杀毒软件禁止

远程地址:192.168.0.102:443

推荐人政策:降级时无推荐人

缓存控制:无存储,无缓存,必须重新验证,max-age=0

连接:关闭

内容长度:52266

内容类型:文本/html;字符集=utf-8

过期时间:1999 年 12 月 4 日星期一 21:29:02 GMT

Pragma:无缓存

接受:/

接受编码:gzip、deflate、br

接受语言:en-US,en;q=0.9

访问控制请求标头:内容类型

访问控制请求方法:GET

连接:保持活动

主机:192.168.0.102

来源:https ://istimuli.co.uk

推荐人:https ://istimuli.co.uk/?code=66b72f8e-400c-4adb-ad42-f4efec391d06

Sec-Fetch-Dest:空

Sec-Fetch-Mode: cors

Sec-Fetch-Site:跨站点

用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 OPR/67.0.3575.79

行动:upload_current_temp

4

0 回答 0