I'm trying to send a simple object via a fetch request to my express server but I keep getting the error when trying to log it.
currently when I log req.body (if I have the header 'Content-Type': 'application/x-www-form-urlencoded') I get:
req body is { '{"password":"dXGT2yY!@2eM6~h-"}': '' }
how Can I extract the value from this object? using JSON.parse(req.body) I get
Unexpected token < in JSON at position 0
I also want to note that when I use the header
{ 'Content-Type': 'application/json'}
req.body logs as {} in my index route.
here is my app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
const bodyparser = require('body-parser')
var logger = require('morgan');
var app = express();
app.use(bodyparser.urlencoded({extended: true})); //include bodyparser
app.use(bodyparser.json()); //include bodyparser
var indexRouter = require('./routes/index');
app.use(express.static("public"));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', indexRouter);
module.exports = app;
index.js (router)
var express = require('express');
var router = express.Router();
const path = require('path');
router.post('/authenticate', function(req, res, next) {
console.log('req body is',JSON.parse(req.body)) //getting error here when parsing
res.send("passconfirmed");
});
module.exports = router;
here is my client's post request
<script type="text/javascript">
$(function(){
//show the modal when dom is ready
$('#loginModal').modal('show');
});
async function postData(url = '') {
const response = await fetch(url, {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify({password: document.getElementById("passholder").value}) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
document.getElementById("loginButton").addEventListener('click',function(){
console.log('sending data',document.getElementById("passholder").value)
postData('http://localhost:3000/authenticate' )
.then(data => {
console.log('returned from server',data); // JSON data parsed by `response.json()` call
if(data === "passconfirmed"){
$('#loginModal').modal('hide');
}
});
})
</script>