It appears that my POST request is being converted to GET somewhere in my REACT client code. This is the reaction code:
function SavePatient(event) { event.preventDefault(); console.log("Saving Patient Data"); console.log(patientData); fetch('http://localhost:3001', { Method: 'POST', Headers: { 'Accept': 'application/json', 'Content-Type': 'multipart/form-data' }, Body: JSON.stringify(patientData), Cache: 'default' });
This is the server code:
function requestListener(req,res) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); console.log(req.url,req.method,req.headers); // console.log(req); //process.exit(); const url = req.url; const body = []; let parsedBody = ""; function readData(chunk) { console.log(chunk); body.push(chunk); } function endReadData(chunk) { parsedBody = Buffer.concat(body).toString(); console.log(parsedBody); } if (url === '/savepatient') { const body = []; req.on('data', readData); req.on('end', endReadData); res.setHeader('Content-Type', 'text/json'); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); res.write('{"name":"John", "age":30, "car":null}'); console.log('Saving...'); fs.writeFileSync('storage/message.txt','TESTE'); return res.end(); } // console.log('Aqui') // res.setHeader('Content-Type', 'text/html'); // res.write('<html>'); // res.write('<head><title>MEDPRO.app server</title></head>'); // res.write('<body><h1>Hello from the MEDPRO.app server!</h1></body>'); // res.write('</html>'); // res.end(); }
The server code works fine and I receive the POST request normally using Postman. The problem is that when I send the request from the client using fetch... it arrives as POST... very strange.
I expected the POST request to reach the server.
Can be found using the Postman test server.
For my client, this is the message the server receives:
/Obtain{ host: 'localhost:3001', connection: "keep alive", 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, such as Gecko) Chrome/112.0.0.0 Safari/537.36',
'sec-ch-ua-platform': '"Windows"', accept:'/', Source: 'http://localhost:3000', 'sec-fetch-site': 'Same site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', Cited by: 'http://localhost:3000/', 'Accept encoding': 'gzip, deflate, br', 'Receptive language': 'en,en-US;q=0.9,es;q=0.8,pt-BR;q=0.7,pt;q=0.6' }
Try setting everything to lowercase in the
fetch
method; this should do the trick as it is case sensitive.like this: