简体   繁体   中英

get jquery post data in node.js

I hope this is not a stupid question or a duplicate but it seems like everywhere I look there is a different answer and I have not been able to get any of them to work...

With jQuery and PHP, I am able to do the following to send and receive data between the front end and back end ->

$.post("logic.php", {
    command: command
}, function(data, status) {
    $("#output").html(data);
}); //jQuery (front-end)


if (isset($_POST['command'])) {
    $command = $_POST['command'];
    if ($command == 'about') {
        echo 'about';
    } else {
        echo 'command not found';
    }
} // PHP (back-end)

The communication works and seems rather simple. Now, I am converting to Node.js and am having a very hard time achieving the same affect. I am not getting any errors but it dosen't seem to be communicating at all... I have tried many different things but here is what I have now ->

$.post("index.js", {
    command: command
}, function(data, status) {
    out(data); /* out is a function i made that puts the data on the page in a nice format */
}); // jQuery (front-end)


var express = require('express');
var bodyParser = require('body-parser')
var app = express();
// Javascript back-end
app.post('/', function (req, res, next) {
    console.log(req.body) ;
}); // Should log command to the console but nothing at all happens

I am very new to node.js but wanted to transition from PHP because I heard about the great AJAX capabilities (which is what my application is based off of)... please help :)

You define bodyParser , but never use it. You have to add it to the express configuration.

app.use(bodyParser.urlencoded());

After this, req.body will not longer be undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM