0

tried to console.log data in node script from a http post

const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));

const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static('public'));

app.post('/do-login', function(req, res) {
    console.log( req.body );
});

and in client, I'm using javascript fetch to send data to node backend

let data = {
    email :'test@domain.com',
    password : 'test'
}

fetch('http://localhost:3700/do-login',{
    method : 'post',
    body : JSON.stringify(data)
}).then(function(response) {
    return response.json();
}).then(function(data) {
    console.log(data);
});

but no luck, it returns an empty object

enter image description here

but, If I use post xmlHttpRequest

var http = new XMLHttpRequest();
var url = 'http://localhost:3700/do-login';
var params = 'email=test@domain.com&password=test';
http.open('POST', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

I'm able to receive the data sent from client. What seems wrong?

enter image description here

Any help, ideas is greatly appreciated.

Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164

1 Answers1

1

Send the request in form-url-encoded. Firstly, create a method that handles formUrlEncoding.

formUrlEncoder(params, formUrlBody){
    
    for (let property in params) {
      let key = encodeURIComponent(property);
      let value = encodeURIComponent(params[property]);
      formUrlBody.push(key + "=" + value);
    }
    return formUrlBody.join("&");
}

Next, call the method which will return all the values encoded so simply pass it in the body.

const url = 'http://localhost:3700/do-login';
const params = {
  email :'test@domain.com',
  password : 'test'
};
const headers = new Headers({
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});

let formUrlBody = [];
formUrlBody = formUrlEncoder(params, formUrlBody);

fetch(url, {
  method: 'POST',
  headers: headers,
  body: formUrlBody
});

You can find more detail regarding fetch here.

Mr Khan
  • 2,139
  • 1
  • 7
  • 22
  • 1
    could you atleast mark it as duplicate or say that you copy pasted it from here https://stackoverflow.com/questions/35325370/post-a-x-www-form-urlencoded-request-from-react-native – bill.gates Sep 11 '20 at 05:37