无法使用esp32从Arduino中的ReactJS网页读取数据

Unable to read data from ReactJS Webpage in Arduino using esp32

我正在创建一个 ReactJS 应用程序,其中包含输入字段 'ssid''Submit' 按钮。我想在按下提交时 将此输入字段数据发送到 esp32。我通过这样做接收数据,但它每隔一个字符就会跳过一次,即如果我写 "React" 并按下提交按钮,Arduino 串行输出显示 "ec??"。

反应代码(index.js):

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class arduinoApp extends Component {
  constructor(props) {
    super(props);
    this.state = { ssid: '', password: '' };
  }
  setSsid(state) {
    this.setState({ ssid: state !== '' })
  }
  componentDidMount() {
    fetch('/inputText')
      .then(response => response.text())
      .then(state => this.setSsid(state));
  }
   Submitted(){
    fetch('/inputText', { method: 'PUT', body: document.getElementById('ssid').value})
      .then(response => response.text())
}
  render() {
    return (
      <div className="ConfigurePage">
        <div>
          <input type="text" id="ssid" name="ssid" />
          <button type="submit" onClick={this.Submitted} >Submit</button>
        </div>
      </div>
    );
  }
}
ReactDOM.render(<arduinoApp/> , document.getElementById('root'));

Arduino 代码:

#include <WiFi.h>
#include "aWOT.h"
#include "StaticFiles.h"

char currentLine;
const char* ssid     = "SSID";
const char* password = "PASSWORD";

WiFiServer server(80);
Application app;


void readSsid(Request &req, Response &res) {
  res.print(currentLine);
}

void updateSsid(Request &req, Response &res) {
  while(req.available())
          {
             currentLine+=req.read();
             Serial.write(req.read());
          }
  Serial.println(currentLine);
  return readSsid(req, res);
}

void setup() {
  Serial.begin(115200);

  WiFi.softAP(ssid, password);
  IPAddress IP = WiFi.softAPIP();

  Serial.println(IP);

  app.get("/inputText", &readSsid);
  app.put("/inputText", &updateSsid);

  app.route(staticFiles());
  server.begin();
}

void loop() {
  WiFiClient client = server.available();

  if (client.connected()) {
    app.process(&client);
  }
}

从网页传输或读取数据时我做错了什么?

非常感谢您的帮助!提前致谢。

问题出在Arduino代码上。在updateSsid上,你的while循环会读取两次(第一次读取数据在这个过程中丢失,第二次被捕获)。

这是一个快速修复,

void updateSsid(Request &req, Response &res) {
    while(req.available())
    {
         currentLine+=req.read();
         //Serial.write(req.read()); // or remove the above line...
    }
    Serial.println(currentLine);  // if removing currentLine, don't forget here
    return readSsid(req, res);
}

或:

void updateSsid(Request &req, Response &res) {
    while(req.available())
    {
        //currentLine+=req.read();
        Serial.write(req.read());
    }
    // Serial.println(currentLine);
    return readSsid(req, res);
}