0

Fetch request through an HTML page. I want to post formData object to the server which is hosted locally.

let formData={
           name:document.getElementById('name').value,
           question:document.getElementById('question').value
         }
   
         let response=await fetch('http://localhost:5000/',{
           method:'POST',
           mode:'no-cors',
           headers:{'Content-Type':'application/json'},
           body:JSON.stringify(formData)
         }).then((res)=>console.log(res)).catch((err)=>console.log(err))
         
       })

The req.body gives an empty object, I also tried using body-parser but it didn't work either.


//--------app.js-------------
const express = require('express');
const app=express();
const port=process.env.PORT || 5000;

app.use(express.json());

app.get('/',(req,res)=>{
    res.send('im alive')
})

app.post('/',(req,res)=>{
    console.log(req.body);
    res.json({status:"okay"});
})

app.listen(5000,()=> console.log('Listening at '+port));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sai Ganesh
  • 11
  • 1
  • 2
  • Try `console.log(req.headers)` in `app.post('/', .... )` to make sure there's a correct `Content-type` header. Also try `console.log(JSON.stringify(formData))` to make sure it stringifies the data as you expect. – Molda Mar 25 '22 at 06:45
  • your headers are being over-written. Please check this. https://stackoverflow.com/questions/38156239/how-to-set-the-content-type-of-request-header-when-using-fetch-api – indolentdeveloper Mar 25 '22 at 08:19
  • @Molda 'content-type': 'text/plain;charset=UTF-8' when I console logged req.headers, – Sai Ganesh Mar 26 '22 at 05:08
  • @indolentdeveloper I tried creating Headers object but still didn't work. – Sai Ganesh Mar 26 '22 at 05:11

2 Answers2

2

The mode:'no-cors' is messing things up. This mode leads to only selected content type headers to be sent.

Allowed list. allowed content types headers: [ ['Content-Type', 'application/x-www-form-urlencoded'], ['Content-Type', 'multipart/form-data'], ['Content-Type', 'text/plain'], ]

So you have 2 options left.

1.Remove 'no-cors' mode.

2.Use content type:application/x-www-form-urlencoded. You would need additional code to convert the json, but it can get complicated.Json to url encoded

indolentdeveloper
  • 1,253
  • 1
  • 11
  • 15
1

Make sure you wait for the data before printing.

fetch('http://127.0.0.1:3000/')
  .then(async data => {
     const res = await data.json() // data is a promise here
     console.log(res)
})
Kuza Grave
  • 1,256
  • 14
  • 15