0

I'm using NodeJS+express and React. The request body's expected output is "tipologia", but it actually returns an empty object. I have looked for similar questions (there a lot of them) but none of these is useful.

client:

function CreateStudyPlan(tipologia){
  return new Promise((resolve, reject) => {
    fetch((URL+'/PianoStudio'), {
      method: 'POST',
      credentials: 'include',
      headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*"
      },
      body: JSON.stringify(tipologia),
    }).then((response) => {
      if (response.ok) {
        resolve(null);
      } else {
        // analyze the cause of error
        response.json()
          .then((message) => { reject(message); }) // error message in the response body
          .catch(() => { reject({ error: "Cannot parse server response." }) }); // something else
      }
    }).catch(() => { reject({ error: "Cannot communicate with the server." }) }); // connection errors
  });
}

server:

// set-up the middlewares
    app.use(morgan('dev'));
    app.use(express.json());
    const corsOptions = {
      origin: 'http://localhost:3000',
      credentials: true,
    };
    app.use(cors(corsOptions));

const isLoggedIn = (req, res, next) => {
  if(req.isAuthenticated())
    return next();
  
  return res.status(401).json({ error: 'not authenticated'});
}

app.post('/PianoStudio', isLoggedIn, async (req, res) => {
  try {
    await dao.createPianoStudio(req.body, req.user.id);   
    res.status(201).json(req.body);
  } catch(err) {
    console.log(err);
    res.status(503).json({error: `Database error during the creation of piano di studi for user ${req.user.id}.`});
  }
});

The problem is that req.body is empty and should not be ( i am expecting it to output part-time): Response (req.body) is empty, but i'm expecting part-time Payload is part-time, not empty

The insert into the DB shows that req.user.id is ok, while req.body is an empty Object: DB insert

--

2 WORDS ON REQUEST ID AND BODY: req.body should be the

body: JSON:Stringify(tipologia)

from the client, while req.user.id is retrieved by the session through the isLoggedIn.

2 WORDS ON HEADERS:

At first i had

headers: {
    'Content-Type': 'application/json',

But it gave me CORS error:

Access to fetch at 'http://localhost:3001/PianoStudio' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So i changed the Headers to

headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*"
      }

as putting 'Content-Type': 'application/json', returns again CORS error.

6
  • 1
    Content-Type: application/json is correct and necessary, you must enable your server for CORS (app.use(require("cors")())). Commented Jun 6, 2022 at 17:22
  • Try moving your middlewares to the top. Commented Jun 6, 2022 at 17:26
  • @HeikoTheißen app.use(cors(corsOptions)); is still required or could cause conflicts with what you suggest? Commented Jun 6, 2022 at 20:19
  • 1
    @Ensar they already are, i just added them later. Sorry, edited Commented Jun 6, 2022 at 20:29
  • If you have app.use(cors(corsOptions)), ignore my app.use(require("cors")()). Commented Jun 7, 2022 at 4:22

1 Answer 1

1

You should try to define tipologia as an object, in the Client: body: JSON.stringify({tip_str: tipologia})

While in your Server, you will retrieve your tipologia as follows: dao.createPianoStudio(req.body.tip_str, req.user.id)

Sign up to request clarification or add additional context in comments.

1 Comment

sounds reasonable, will try as soon as i can. Thanks

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.