5

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}`));
2
  • Is the error that gets thrown inside body-parser? Random idea, if body-parser isn't needed as an additional middleware, perhaps Express is trying to parse the JSON twice, and thus you just need to remove this line? app.use(bodyParser.json()); Commented Aug 10, 2021 at 0:01
  • why do you think the req.body has a post property? you're not sending one
    – Bravo
    Commented Aug 10, 2021 at 0:02

2 Answers 2

10

First, you no longer need to explicitly include body-parser. It is now bundled with Express and available via the following functions...

app.use(express.json())
app.use(express.urlencoded()) // extended = true is the default

The JSON parsing middleware is configured to handle objects by default. While a string literal like "hello world" is valid JSON, it's not what the framework expects, hence your error.

Since you appear to be trying to access req.body.post, you should send your data with such a structure

fetch("http://myip:3000/wow/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ post: "hello world" })
})

Alternatively, if you did want to post a JSON string literal, you would need to configure your JSON middleware like so

app.use(express.json({ strict: false }))

strict

Enables or disables only accepting arrays and objects; when disabled will accept anything JSON.parse accepts.

in which case your "hello world" string would appear in req.body

1
  • It is kind of crazy that you have to do extra paramter configuration to have express.json() middleware accept the full json specification (which includes blank strings, numbers, ... But thank you, app.use(express.json({ strict: false })), did the trick. Commented Jun 22, 2022 at 9:37
-1

for me, adding

  res.header('Access-Control-Allow-Origin', '*');

solved the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.