简体   繁体   English

使用node.js在服务器和客户端之间进行通信

[英]communicate between a server and a client with node.js

I have a node.js Server:- 我有一个node.js服务器:

// *********** Server that receives orders ************ //

// to use features of the http protocol. // 
var http = require('http');

// initialize to empty string. //
var req = "";

// create the server that will receive an order Request. //
var server = http.createServer(function(req,res) {
  res.writeHead(200, {'content-type': 'text/plain'});
  // when data is successfully received, a success message is displayed. //
  res.on('data', function(data){
        req += data; // received data is appended. //
       console.log("We have received your request successfully.");
  });
});

// An error message is displayed - error event. //
   server.on('error', function(e){
   console.log("There is a problem with the request:\n" + e.message);
  });

// server listens at the following port and localhost (IP). //
server.listen(8000, '127.0.0.1');

and then I have a node.js Client:- 然后我有一个node.js客户端:

var http = require("http"); 
var querystring = require("querystring");
var postOrder = querystring.stringify({
        'msg': 'Hello World!'
});

var options = {
        hostname: '127.0.0.1',
        port: 8000,
        path:'/order',
        method:'POST',
        headers:{
           'Content-Type' :'application/x-www-form-urlencoded',
           'Content-Length' : postOrder.length
        }
};


var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

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

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

I am trying to figure out how I can make the client post its order to the server and get a response back from the server...either a success message or an error message...using command line. 我正在尝试弄清楚如何使客户端将其订单发布到服务器并从服务器获得响应...成功消息或错误消息...使用命令行。

currently I run the server on cmd line $ node server.js 目前,我在cmd行$ node server.js上运行服务器

and then a run the client $ node client.js 然后运行一个客户端$ node client.js

but i get no responses. 但我没有回应。

I think that have problems from the server: The Server must be: 我认为服务器存在问题:服务器必须是:

http.createServer(function(req, res) {
    if (req.method == 'GET') {

    } else if (req.method == 'POST') {
        var body = '';
        req.on('data', function(data) {
            body += data;
        });
        req.on('end', function() {
         console.log("We have received your request successfully.");
        });
    }
    res.end("ok");
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM