I am attempting to follow this tutorial (https://levelup.gitconnected.com/introduction-to-express-js-a-node-js-framework-fa3dcbba3a98) to connect Express with React Native via . I have a server.js script running which connects to the client (App.tsx) on my ip, port 3000. The server and app are run simultaneously on the same device in different terminals. The server is able to recieve GET requests just fine, as when the app launches, a useEffect function calls a GET request, and the server sends a message. However my POST requests, which contain a content body set to JSON.stringify("hello world")
are not working. and the server script returns the following error anytime I press the button:
SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
...
I'm assuming I am sending in badly formatted json, or haven't set the content type properly, but I haven't been able to figure out the exact problem.
App.tsx (where myip is my ip address):
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View, ScrollView, TouchableOpacity, TextInput } from 'react-native';
export default function App() {
const [response, setResponse] = useState();
useEffect(() => {
fetch("http://myip:3000/get")
.then(res => res.json())
.then(res => console.log(res.theServer))
}, []);
async function handleSubmit() {
console.log('button press');
const response = await fetch("http://myip:3000/wow/post", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify("hello world")
});
const body = await response.text();
setResponse({ responseToPost: body });
}
return (
<View style={styles.container}>
<TouchableOpacity onPress={handleSubmit}>
<Text>Submit</Text>
</TouchableOpacity>
</View>
}
...
});
server.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/get", (req, res) => {
res.send({ theServer: "hElLo FrOm YoUr ExPrEsS sErVeR" });
});
app.post("/wow/post", (req, res) => {
console.log(req.body);
res.send(`Here is what you sent me: ${req.body.post}`);
});
app.listen(port, () => console.log(`listening on port ${port}`));
app.use(bodyParser.json());
post
property? you're not sending one