SyntaxError: Unexpected token in JSON at position 0 Express

Viewed 2535

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}`));
1 Answers

First, stop using body-parser. Express has its own request body parsing middleware.

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

Related