无法读取节点

时间:2015-07-29 13:26:52

标签: node.js http

我正在尝试在客户端的JQuery和服务器端的节点之间建立通信。我使用了带回调的ajax但是

'req.on('data', function (data) {'

似乎不起作用。

以下是代码:

客户方:

index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>

  <body>
    <h1><%= title %></h1>
      <input type="button" id="stopButton" value="Button1"/>
      <input type="button" id="stopButton2" value="Button2"/>
    <p>Welcome to <%= title %></p>
  <ul id="fruits">
  <li id= "1" class="apple">Apple</li>
  <li id = "2" class="orange">Orange</li>
  <li id = "3" class="pear">Pear</li>
</ul>
  <script type="text/javascript">
      $(document).ready(function () {
        $.ajax({
        url: 'http://localhost:3000',
        dataType: "jsonp",
        data: '{"data": "Hello from Client"}',
        type: 'POST',
        jsonpCallback: 'callback', 
        success: function (data) {
            var ret = jQuery.parseJSON(data);
            console.log(ret.msg);
            $('[class="apple"]').html(ret.msg);
        }
    });
 });
 </script> 
 </body>
</html>

服务器端: 的node.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , request = require ('request')
  , cheerio = require ('cheerio')
  , $;
 

var app = express();
//console.log($('[class = "orange"]').attr('id'));
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(function (req, res) {
  var body="";
  console.log('Request received: ');
  req.on('data', function (chunk) {
    body +=chunk;        
  });
  req.on('end', function(){
	console.log("Body: "+body);
	res.write('Hello from Server');
	res.end();
 });

}).listen(3000);

我在服务器端控制台日志中收到“收到请求:”。此外,我能够在HTML上查看“来自服务器的Hello”。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您似乎忘了留言:res.end();

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    req.on('data', function (data) {
        console.log(data);
        res.write('Hello from Server');
        res.end();
    });