首页 > 解决方案 > Node.js 向 vps 服务器发送数据

问题描述

我正在尝试将数据从 client.js 发送到托管在 vps 上的服务器,然后将另一个数据返回给 client.js。

像这样:client.js >data> server.js >data2> client.js

我的 client.js 文件:

var http = require('http');

var option = {
    hostname : "51.x.x.x" ,
    port : 8000 ,
    //data?: "{}",
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       });
    });
    request.end(); 
/* server.js sending data to client.js but I don't know how to send data to server.js */

和 server.js 文件

var http = require('http');

http.createServer(function (req, res) {
    if (req.method == 'POST') {
        console.log('Res > post');
        res.end('data from server.js (post)')
    }
    else {
        console.log("Res > get");
        res.end('data form server.js (get)');
    }
}).listen(8000);
console.log('Running server with port 8000...');

那么,有没有办法将数据从 client.js 发送到 server.js ?

标签: javascriptnode.js

解决方案


您的 client.js 也是节点应用程序吗?如果是这样,websockets 可能会帮助您建立双向通信。 https://socket.io/get-started/chat/


推荐阅读