1

Learning nodejs and trying to post a form from HTML (with image upload) to nodejs (express) but the request.body returning empty object.

Tried few solutions on this site but no one is working.

Here is my code for creating a dynamic form. (HTML)

function show(data) {
const d = data.temp_form;
let content = ''
// console.log(d)

d.forEach((item) => {
    if (item === 'image_backup' || item === 'image_banner') {
        content += `<label for='${item}'>${item}</label><input name='${item}' type='file' id='${item}' value=''><br/>`
    }else{
        content += `<label for='${item}'>${item}</label><input name='${item}' type='text' id='${item}' value=''><br/>`
    }
    
})
content += ` <input type="submit" id="handle_submit">`


getFormContianer.innerHTML = content

}

Code handling form submit

async function handleForm(e) {
e.preventDefault();
let dataForm = new FormData(e.target)

let obj = {}
dataForm.forEach((value, key) => {
    obj[key] = value
    if( typeof value === 'object'){
       console.log(value.name)
       obj[key] = value.name
    }
});

let data = JSON.stringify(obj);

 await fetch(file_api, {
        method: 'POST',      
        body: data
    }).then((res)=>{
        return res.json();
    }).then((data)=>{
        console.log('api err: '+data);
    }).catch((err) =>{
        console.log('api err: '+ err)
    })
    
}

Then, in my nodejs

const express = require('express');
const cors = require('cors'); 
const config = require('./config')
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
const app = express()

const templates = require('./routes/templates-routes');
const files = require('./routes/files-routes');


app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));  
app.use(upload.array()); 


app.use(express.static('public'))
app.use('/api', templates.routes);
app.use('/create', files.routes);


app.listen(config.port, () => {
    console.log(`Example app listening at http://localhost:${config.port}`)
  })

and in the route.js

const express = require('express');
const router = express.Router();
const {replaceValue } = require('../controllers/filesController');
router.post('/file', replaceValue);    
module.exports={
    routes: router
}

for the fileController.js

const replaceValue = (request, response) =>{
console.log(request.body)
response.send(request.body)}

Hope that can get some comment for you, thank you so much!

1 Answer 1

4
let data = JSON.stringify(obj);

 await fetch(file_api, {
        method: 'POST',      
        body: data

You are passing a string to body and haven't specified a Content-Type header so fetch will generate a Content-Type: text/plain header.

Since plain text isn't JSON, the JSON parsing middleware you have set up in Express won't process it.

 await fetch(file_api, {
        method: 'POST',      
        headers: {
          'Content-Type': 'application/json'
        },
        body: data

Note that this will make it a preflighted request, so make sure you follow the instructions for the CORS module to support that.

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

1 Comment

It is weird as the very first time I did added the content-type but it is not working, and now work perfectly after posted question here. You saved me, thank you!

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.