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):
The insert into the DB shows that req.user.id is ok, while req.body is an empty Object:
--
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.
CodePudding user response:
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)