U
U
UNy2018-05-04 17:45:42
JavaScript
UNy, 2018-05-04 17:45:42

Passing data from client to server?

How to make an ajax request? There is an html file with a button. There is a button click handler that should send data to the server. How to write url correctly?

function but() {
        let a = 3;
        let xhr = new XMLHttpRequest();
        xhr.open("POST", "http://localhost:8080/");
        xhr.send(a);
        document.write(res.text)
    }

I receive data on the server:
app.post('/', function (req, res) {
    let a = req.name;
    console.log(a);
});

But it outputs undefined. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2018-05-04
@UNy

Need bodyParser

// клиент

function but() {

  var xhr = new XMLHttpRequest();
    xhr.open( 'POST', '/ajax' );
    xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
    xhr.send( 'field=value' );

}

// сервер

app.use( bodyParser.json(), bodyParser.urlencoded({ extended: true }) );

app.post( '/ajax', function (req, res) {

  console.log( req.body );

});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question