Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
SyntaxError: Unexpected token in JSON at position 0 Express

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}`));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda