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 :'[email protected]',
    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 protected]&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.

4
  • 1
    your fetch is sending JSON ... your XHR is sending application/x-www-form-urlencoded ... the two pieces of code are not comparable Commented Sep 11, 2020 at 4:56
  • 1
    solution 1) send x-www-form-urlencoded data when using fetch, or 2) set content-type to application/json in your fetch request Commented Sep 11, 2020 at 4:57
  • @JaromandaX I would like to accept your answer, please post it. Commented Sep 11, 2020 at 5:06
  • 2
    Answer by someone else is just as good - I won't be answering Commented Sep 11, 2020 at 5:06

1 Answer 1

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 :'[email protected]',
  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.

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

1 Comment

could you atleast mark it as duplicate or say that you copy pasted it from here stackoverflow.com/questions/35325370/…

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.