Issue
I'm currently working on a simple React Native which sends to a Node.js server hosted on a Raspberry Pi3B an order to switch on or off a led.
React Native code :
import React from 'react';
import {StyleSheet, Text, View, Button} from 'react-native';
export default class App extends React.Component {
constructor(props){
super(props);};
led(couleur){
fetch('http://XXX.XXX.XXX.XXX:XXX/switchOnOff', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},body: JSON.stringify({'couleur': couleur}),
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View>
<View style={styles.bleu}>
<Button title="Bleu" color='blue' onPress={() => this.led('bleu')}/>
</View>
</View>
);
}
}
On the Raspberry, I have the following for my Node.js server :
var express = require('express');
var fs = require("fs");
var bodyParser = require('body-parser');
var Gpio = require('onoff').Gpio,
led14 = new Gpio(14, 'out');
var app = express();
app.use(bodyParser.json());
var allumer = false;
app.post('/switchOnOff', function (req, res) {
coul = req.body['couleur'];
console.log('working!');
var val = !allumer ? 1 : 0;
if (coul == 'bleu'){
led14.writeSync(val);}
led14.watch((err, mess) => {
if (err){throw err }})
allumer = !allumer;
}
});
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
strangely, this is working 5 times in a row (I get in the server console "working!" printed five times, and the led is toggled on/off).
But then I get the following error :
From then, I'm not able to send data to the server using the React Native app...
Has anyone any idea ?
Thanks
Solution
Actually I got it :
the error was coming from the server side: I was missing one line of code res.end()
which ends each request
Modified server side code :
app.post('/switchOnOff', function (req, res) {
coul = req.body['couleur'];
console.log('working!');
var val = !allumer ? 1 : 0;
if (coul == 'bleu'){
led14.writeSync(val);}
led14.watch((err, mess) => {
if (err){throw err }})
allumer = !allumer;
}
//#########solving line##########
res.end
});
Answered By - ere