When doing a GET request in react native, on a local API I have written I get the error, 'JSON Parse error: Unrecognised token '<''. When doing a GET request via Postman, the JSON I see is:
{"question":"Which three Spaniards played in the 2007 Champions League Final?","answer":"Pepe Reina, Alvaro Arbeloa, Xabi Alonso","id":1}
This is my react native code:
_onPressButtonGET: function() {
fetch("http://localhost:8088/id/1", {method: "GET"})
.then((response) => response.json())
.then((responseData) => {
AlertIOS.alert(
"GET Response",
"Search Query -> " + responseData.question
)
})
.done();
},
render: function() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={this._onPressButtonGET} style={styles.button}>
<Text>GET</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this._onPressButtonPOST} style={styles.button}>
<Text>POST</Text>
</TouchableHighlight>
</View>
);
},
This is my API's code:
var express = require('express');
var app = express();
var fs = require('fs');
var random = require('random-number-generator')
app.get('/teasers', function (req, res) {
fs.readFile(__dirname + '/' + 'teasers.json', 'utf8', function (err, data) {
console.log(data);
res.end(data);
});
});
app.get('/teasers/:id', function (req, res) {
fs.readFile(__dirname + '/' + 'teasers.json', 'utf8', function (err, data) {
users = JSON.parse(data);
var user = users['question' + req.params.id];
console.log(user);
res.end(JSON.stringify(user));
});
});
var server = app.listen(8088, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://localhost:%s", host, port);
});
via jord
No comments:
Post a Comment