I am stumped. I am making a simple fetch() to the backend where I log request body i.e. console.log(req.body.form_data)
Problem: returning {} empty json object.
Attempt: I have installed body-parser i.e
app.use(express.urlencoded({ extended: true }));
// body parser - parse json in body.requests
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({
extended: true })); // to support URL-encoded bodies
What is wrong?
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// body parser - parse json in body.requests
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({
extended: true // to support URL-encoded bodies
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
let users = [];
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
if(req.body.form_data) {
console.log(req.body.form_data)
// res.json(users);
}
console.log(req.body)
res.render('index', { title: 'TO DO APP' });
});
module.exports = router;
myscript.js
document.getElementById("listForm").addEventListener('submit', function(e) {
e.preventDefault();
const fname = document.getElementById("fname").value;
const list_name = document.getElementById("list-name").value;
const list_date = document.getElementById("list-date").value;
var form_data = {
fname: fname,
list_name: list_name,
list_date: list_date
};
console.log(form_data );
// AJAX fetch()
fetch('/', {
method: 'POST',
headers: new Headers(),
body: form_data
}).then(function(response) {
console.log("response..");
return response.json();
}).then(function(user_json) {
console.log(user_json);
});
});
index.pug
extends layout
block content
h1= title
p First, create your list
form#listForm(method="POST" action="/")
input(type='text' id="fname" name='fname' autofocus placeholder="your name")
input(type='text' id="list-name" name='list-name' autofocus placeholder="name your list")
input(type='date' id="list-date" name='list-date' autofocus placeholder="today's date")
button(type='submit') Create List
I suppose you need to pass the content-type
header with your request which you're not sending currently. Also you would need to convert it into a JSON string by using JSON.stringify
like below.
let headers = new Headers();
headers.append('content-type','application/json');
fetch('/', {
method: 'POST',
headers: headers,
body: JSON.stringify(form_data)
}).then(function (response) {
console.log("response..");
return response.json();
}).then(function (user_json) {
console.log(user_json);
});