I have the following project: I want to send data from a web browser to an STM32H743 microcontroller via Javascript. I am using the lwip stack on the microcontroller. If I now send data to my STM server with the following Javascript code, I receive the sent string with the additional HTTP add-ons on my microcontroller.
const serverAddress = "http://192.168.1.87:8000";
function sendDataToServer(data) {
console.log("Sending data to the server.");
fetch(serverAddress, {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
body: data
})
.then(response => {
console.log(response);
if (!response.ok) {
throw new Error('Network response was not ok.');
}
console.log('Data successfully sent to the server.');
})
.catch(error => {
console.error('Error when sending data to the server:', error);
});
}
// Function call from a button-event
sendDataToServer('hello server!');
The received string on the STM32:
"POST / HTTP/1.1\r\nHost: 192.168.1.87:8000\r\nConnection: keep-alive\r\nContent-Length: 12\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... US;q=0.8,en;q=0.7\r\n\r\nhello server!"
With the following callback function I send the string response
HTTP/1.1 200 OK\r\n
Content-Length: 0\r\n\r\n
with the function tcp_write() back to the client, as shown below.
void serverReceiveCallback(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) {
if (p != NULL && err == ERR_OK) {
// Copy the received Data in a local buffer.
char rxBuf[rxBufferSize];
memcpy(rxBuf, p->payload, p->len);
// Terminate the string.
rxBuf[p->len] = '\0';
// Is the received String a post?
if (p->len > 0) {
if (strncmp(rxBuf, "POST", 4) == 0) {
// Respond to the post.
const char response[] = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; // SENT
tcp_write(tpcb, response, strlen(response), 0);
}
}
// Free the pbufs
tcp_recved(tpcb, p->tot_len);
pbuf_free(p);
}
}
Since I am working with the lwip package on the transport layer, I have to do the header for the HTTP protocol myself and obviously I am doing something wrong there. The browser then tells me:
net::ERR_INVALID_HTTP_RESPONSE
Do I have to design the header differently so that the fetch API of Javascript is satisfied?
Many thanks for your help!
Touby