[英]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 -> 使用jQuery和PHP,我可以执行以下操作来在前端和后端之间发送和接收数据->
$.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.
现在,我正在转换为Node.js,并且很难获得相同的效果。 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 :) 我是node.js的新手,但想从PHP过渡,因为我听说了强大的AJAX功能(这是我的应用程序所基于的功能)...请帮助:)
You define bodyParser
, but never use it. 您定义了
bodyParser
,但是从不使用它。 You have to add it to the express configuration. 您必须将其添加到快速配置中。
app.use(bodyParser.urlencoded());
After this, req.body
will not longer be undefined
. 此后,
req.body
将不再是undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.