我正在使用html页面中的ajax函数将表单数据发送到node.js服务器,如果我使用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>
解决方法
您需要一个中间件来解析正文的帖子数据.您可以尝试
bodyParser.首先,您应该安装它:
$npm install body-parser
然后只需要并使用它:
var express = require('express'),bodyParser = require('body-parser'),path = require('path'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.post('/filter',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,{'Content-Type': 'text/html'}); res.end("hello"); }) };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。