如何在html中使用ajax方法从节点服务器获得响应

我发送表单数据到node.js服务器在html页面中使用ajax函数,如果我使用post方法,我不能看到任何东西在控制台以及警报框。

如果我在ajax和app.js文件中使用get方法,我得到了警报,但我不是在app.js服务器控制台中的任何味精

app.js

var express = require('express') , routes = require('./routes') , manage = require('./routes/user') , http = require('http') , path = require('path'); var app = express(); app.post('/filter', routes.filter); http.createServer(app).listen(app.get('port'), "172.29.59.65", function(){ console.log('Express server listening on port ' + app.get('port')); }); 

index.js

 exports.filter = function(req, res){ req.on('data', function (chunk) { console.log("Received body data", chunk.toString()); //chunk is received, process it as you need }) req.on('end', function() { // http request is competed, send response to client res.writeHead(200, "OK", {'Content-Type': 'text/html'}); res.end("hello"); }) }; 

client.html

 <html> <head> <script> function myFunction() { var region=document.getElementById("region").value; var os=document.getElementById("os").value; alert(region+os); var data = {}; data.region = region; data.os = os; $.ajax({ type: 'POST', jsonpCallback: "callback", datatype: 'jsonp', data: JSON.stringify(data), //contentType: 'application/json', url: 'http://172.29.59.65:3000/filter', success: function(data) { alert(data); console.log(JSON.stringify(data)); }, error: function (xhr, status, error){ console.log('Failure'); alert("failure"); }, }); } </script> </head> <body> <form> <input type="text" id="region" name="region"/> <input type="text" id="os" name="os"/> <input type="button" value="search" class="fil_search" onclick="myFunction()"/> </form> </body> </html> 

我的问题是发送数据到节点服务器,并从节点服务器接收数据到html页面如何实现这一点。 请帮我解决这个问题。

你需要一个中间件来parsing主体的后期数据。 你可以尝试bodyParser 。 首先,你应该安装它:

 $ npm install body-parser 

然后只需要和使用它:

 var express = require('express') , bodyParser = require('body-parser') , routes = require('./routes') , manage = require('./routes/user') , http = require('http') , path = require('path'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.post('/filter', routes.filter); http.createServer(app).listen(app.get('port'), "172.29.59.65", function(){ console.log('Express server listening on port ' + app.get('port')); }); 

现在你的POST参数将被存储在req.body

 exports.filter = function(req, res){ console.log("Received body data", req.body); res.writeHead(200, "OK", {'Content-Type': 'text/html'}); res.end("hello"); }) };