Arduino POST request to Laravel API



嗨,几天我正在尝试开始使用Arduino Uno Wifi rev2进行简单的项目。范围是从卡或芯片读取 rfid 数据,将 rfid 代码发送到网络服务器并从中读取响应。响应将包含分配给已发送 RFID 代码的用户名称。我正在尝试通过将 POST 请求从 Arduino 发送到 laravel API 来实现这一点 - 之后来自 laravel 将使用 rfid 用户的名称发送响应。 但我什至没有从读取 rfid 数据开始,因为我只是将 POST 请求发送到网络服务器并从服务器读取响应。

这是Arduino代码:

#include <WiFiNINA.h>
#include <ArduinoHttpClient.h>
char ssid[] = "SSID_SECRET";
char pass[] = "PASS_SECRET";
int port = 80;
const char serverAddress[] = "https://www.schedy.sk";  // server name
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass); 
delay(5000);
}
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
IPAddress ip = WiFi.localIP();
IPAddress gateway = WiFi.gatewayIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making POST request");
String postData = "rfid=abcde&test=12";
Serial.print("Post Data Length: ");
Serial.println(postData.length());
client.beginRequest();
client.post("/api/rfids");
client.sendHeader("Content-Type", "application/x-www-form-urlencoded");
client.sendHeader("Content-Length", postData.length());
//client.sendHeader("X-Custom-Header", "custom-header-value");
client.beginBody();
client.print(postData);
client.endRequest();
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}

拉拉维尔API。出于测试目的,我在/routes/api .php中定义了简单的路由:

Route::middleware('auth:api')->get('/user', function (Request $request)) {
return $request->user();
});
Route::get('/rfids', 'RfidController@index');
Route::post('/rfids', 'RfidController@store');

在 RfidController 中.php是:

public function index()
{
return "get test";
}
public function store(Request $request)
{
return response("post test")
}

我尝试发布并收到带有 url https://reqbin.com/的请求:https://www.schedy.sk/api/rfids。一切看起来都很好,但是使用Arduino,我仍然得到状态代码400:

making POST request
Post Data Length: 17
Status code: 400
Response: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at kmbtwo.vps.websupport.sk Port 80</address>
</body></html>
Wait five seconds

我对这个问题感到非常绝望。我尝试了几个库和过程,但仍然得到 400 状态代码或 -3。在服务器中 - apache2 日志我无法获得有关问题的更多信息......只是有人尝试向/api/rfids 发出 POST 请求,但答案是 400。不知道原因。有人可以帮助我吗?

问题出在库 - ArduinoHttpClient.h。使用此库,无法发出https请求。我已经用wifinina.h解决了它,我能够从服务器获得成功的答案。

最新更新