infinitezero
infinitezero

Reputation: 2077

Express receives empty request and client does not receive an answer on different ports

I have a small react client that runs on port 3000 and a small express server that runs on port 3001. When I click a button, a request is sent to the server. However, the POST request prints an empty body and the response is not delivered. The server correctly identifies a POST or GET request though. Chrome's console prints:

Error: SyntaxError: Unexpected end of input (at App.tsx:41:1)
at App.tsx:41:1
(anonymous) @ App.tsx:50
Promise.catch (async)
buttonClick2 @ App.tsx:48
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ >react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent

App.tsx (Client)

import { Button, Typography } from '@mui/material';
import { useState } from 'react';

function App() {
  const [msg, setMsg] = useState("No Request Sent")

  const data = { username: 'example' };

  const buttonClick = () => {    
    fetch('http://127.0.0.1:3001', {
      method: 'POST',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    }).then(
      (response) => {
        console.log(response);
        return response.json();
      }
    ).then(
      (data) => {
        setMsg(data.msg);
        console.log('Success:', data);
        return data;
      }
    ).catch((error) => {
        console.error('Error:', error);
      }
    );
  };

  const buttonClick2 = () => {    
    fetch('http://127.0.0.1:3001', {
      method: 'GET',
      mode: 'no-cors',
    }).then(
      (response) => {
        console.log(response);
        return response.json();
      }
    ).then(
      (data) => {
        setMsg(data.msg);
        console.log('Success:', data);
        return data;
      }
    ).catch((error) => {
        console.error('Error:', error);
      }
    );
  };

  return (
    <div>
      <Typography variant="h1">{msg}</Typography>
      <Button onClick={buttonClick}>Click</Button>
      <Button onClick={buttonClick2}>Click2</Button>
    </div>
  );
}

export default App;

server.ts

const express = require( "express" );
const app = express();
const port = 3001;

const cors = require('cors');
app.use(cors({
    origin: 'http://127.0.0.1'
}));

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.get('/', (req:any, res:any) => {
    console.log("GET");
    res.json({msg: 'GET request to the homepage'})
});
  
app.post('/', (req:any, res:any) => {
    console.log("POST: ", req.body);
    res.json({msg: 'POST request to the homepage'})
});

app.listen( port, () => {
    console.log( `server started at http://localhost:${ port }` );
} );

What is wrong with this approach or how can I debug it? I've read similar questions/answer but the answer was either related to CORS policy (which I think I took care off) or to the order off my express middleware (which I think I also took care of).

Upvotes: 0

Views: 113

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

res.send('GET request to the homepage') send a string, not JSON. return response.json(); tries to parse response body as a JSON and fails.

Upvotes: 0

Related Questions