Enes Giray
Enes Giray

Reputation: 326

How to access the data I post from client-side (NodeJs)

I collect some data in JS;

var dataset = {
    "name" : undefined,
    "pass" : undefined,
    "email" : undefined,
    "birthday" : undefined,
    "agree" : false
}

function data () {

    dataset = {
        "name" : document.getElementsByName("name")[0].value,
        "pass" : document.getElementsByName("pass")[0].value,
        "email" : document.getElementsByName("email")[0].value,
        "birthday" : document.getElementsByName("birthday")[0].value,
        "agree" : false
    }

    if(document.getElementById("signupcheck").className.search("active") > -1) dataset.agree = true;

}

And have a NodeJs page

var express = require("express");
var app = express();

app.use(express.static('public'));

app.get("/",function(req,res){
    res.sendFile(__dirname + "/index.html");
})

I want to post the array 'dataset' to server-side, and access in NodeJs page, but I can't. I've tried to send with Ajax like in code but I've failed:

const xhttp = new XMLHttpRequest();
xhttp.open("POST", "/example");
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.send("name=weweww&urd=sss");

NodeJs:

app.post("/example", function(req,res) {
  console.log(req.body)
})

It returns "undefined" on the terminal. How can I access the data I post from client-side?

Upvotes: 1

Views: 563

Answers (1)

Anis
Anis

Reputation: 1220

you need to use body-parser module of node js to get the data in req.body

npm install body-parser

in app.js

var bodyParser = require('body-parser')

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

for more detail

Express body parser Body-parser NPM

Upvotes: 1

Related Questions