-1

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>
monsterpiece
  • 739
  • 2
  • 12
  • 34
  • 1
    Use the Network pane in browser devtools to inspect the response body. You’ll likely find it’s an HTML document rather than JSON. And also likely it’s a 4xx or 5xx error rather than a 200 OK response. – sideshowbarker May 24 '20 at 05:04
  • Why are you using `JSON.parse(req.body)`? `req.body` is supposed to be an object already. – zishone May 24 '20 at 05:16
  • @sideshowbarker I have checked the network panel and I simply get a 500 error that the request failed. I then changed around my content type to application/json and removed json.parse() from my server. Then I checked the network panel again and the request simply remains pending and doesn't seem to time out however the payload is correct but shows as undefined in my express app when logging req.body.password – monsterpiece May 24 '20 at 05:31
  • Does this answer your question? [body parser logging empty object in express router](https://stackoverflow.com/questions/61975632/body-parser-logging-empty-object-in-express-router) – Prathamesh More May 24 '20 at 05:43
  • I guess while sending you need to `JSON.stringify` the body? – ABGR May 25 '20 at 16:27

3 Answers3

1

While sending the fetch request, we need to strigify the body.

body: JSON.stringify({password: document.getElementById("passholder").value} ),
ABGR
  • 4,631
  • 4
  • 27
  • 49
  • thanks, I missed that, however I still get the same output in my server after stringifying the data object { '{"password":"whatever I send from client"}': '' }, I have updated my client code to reflect your suggestion – monsterpiece May 25 '20 at 20:14
0

Please use bodyParser in your index.js or wherever express Applicatio is initialized

const express = require('express');
const bodyParser = require('body-parser');


// create app by calling express()
const app = express();

// using the body parser
app.use(bodyParser.json());

Then in your route

router.post('/authenticate', function(req, res, next) {
  const { password } = req.body;
  console.log('req body is', req.body);
  console.log('password is', password );
  res.send("passconfirmed");
});

Vimal Munjani
  • 280
  • 1
  • 8
  • Yes I am including body-parser in my app.js file so this isn't the issue for me. Body parser does allow me to log req.body, however req.body.password will be undefined – monsterpiece May 25 '20 at 15:49
-1

It seems body parser was not the issue, the object is logged as JSON already. I just needed to access the strings inside

monsterpiece
  • 739
  • 2
  • 12
  • 34