从服务器向客户端发送响应[node.js]

时间:2013-11-18 20:31:51

标签: javascript node.js http client-server

我想获取Google的HTML源代码页并将其传回客户端。我无法使用以下代码。可能导致问题的原因是什么?

没有显示警告框(客户端代码)。该方法和主机是www.google.com

服务器:

/**
 * Module dependencies.
 */

  require('coffee-script');

  var express = require('express')
   , routes = require('./routes')
   , user = require('./routes/user')
   , http = require('http')
   , path = require('path')
   , connect = require('./node_modules/connect')
   , sharejs = require('./node_modules/share');
  var tempServ = require('./router/serverSideCode');

  var app = express();

  // 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(express.cookieParser('your secret here'));
  app.use(express.session());
  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('/temp', tempServ);

var options = {db: {type: 'none'}}; 

// Attach the sharejs REST and Socket.io interfaces to the server
sharejs.server.attach(app, options);

app.listen(8000, function(){
    console.log('Server running at http://127.0.0.1:8000/');
});

客户端:

   request = $.ajax({
        type: "GET",
        url: "/temp",
        data: "",
    }).done(function(res){
        alert("message received : " + res);
    });

ServerSide.js

   var http = require('http');  
    var options = {
      host: 'www.google.com',
      port: 80,
      url: '/temp',
      method: 'GET'
};

var body = '';

var req = http.request(options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    body+=chunk;   // console.log('BODY: ' + chunk);

  });
  res.on('end', function(){
    console.log(body)
   });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});


// write data to request body
req.write(body);
req.end();

0 个答案:

没有答案