簡體   English   中英

使用node.js在服務器和客戶端之間進行通信

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

我有一個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');

然后我有一個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();

我正在嘗試弄清楚如何使客戶端將其訂單發布到服務器並從服務器獲得響應...成功消息或錯誤消息...使用命令行。

目前,我在cmd行$ node server.js上運行服務器

然后運行一個客戶端$ node client.js

但我沒有回應。

我認為服務器存在問題:服務器必須是:

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