我目前正在研究一个简单的React Native,该命令将Raspberry Pi3B上托管的Node.js服务器发送命令以打开或关闭LED。
反应本机代码:
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>
);
}
}
在Raspberry上,我的Node.js服务器具有以下内容:
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)
})
奇怪的是,它连续工作了5次(我在服务器控制台中看到“正在工作!”打印了5次,并且LED被打开/关闭了。)
但是随后出现以下错误:
从那时起,我无法使用React Native应用程序将数据发送到服务器...
有人有什么主意吗?
谢谢
答案 0 :(得分:0)
实际上我知道了:
该错误来自服务器端:我缺少一行代码class RegisterForm2(forms.Form):
gender = forms.ChoiceField(label="Género", choices = UserRegister.gender_choices, required=True)
birthdate = forms.DateField(widget = forms.SelectDateWidget, localize=True)
class meta:
model = UserRegister
fields = ['gender',
'birthdate']
结束每个请求
修改后的服务器端代码:
res.end()