2016-12-16 107 views
4

我是node.js的新手。我正在嘗試使用unix套接字來設置客戶端服務器連接,其中我的客戶端請求位於node.js並且在後臺運行的服務器將處於運行狀態。Node.js:通過unix套接字發送GET請求

客戶端代碼:

var request = require('request'); 

    request('http://unix:/tmp/static0.sock:/volumes/list', function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
      console.log(body) 
     } else { 
      console.log("In else part of the receiver" + response.statusCode + body) 
     } 
    } 


}) 

當我嘗試寫在走它是服務器通信顯示與HTTP error: 400 Bad Request: malformed Host header'

同樣的工作:

curl -X GET --unix-socket /tmp/static0.sock http://:/volumes/list 

不知道是什麼我的要求有誤。我們需要發送標題嗎?我期待JSON響應。

+0

https://nodejs.org/api/net.html#net_server_listen_path_backlog_callback – Adiii

+0

看到這也http://stackoverflow.com/questions/7045614/can-node-js-listen-on-unix-socket – Adiii

回答

5

要做到這一點,而無需使用請求模塊,請嘗試以下操作:

const http = require('http'); 

const options = { 
    socketPath: '/tmp/static0.sock', 
    path: '/volumes/list', 
}; 

const callback = res => { 
    console.log(`STATUS: ${res.statusCode}`); 
    res.setEncoding('utf8'); 
    res.on('data', data => console.log(data)); 
    res.on('error', data => console.error(data)); 
}; 

const clientRequest = http.request(options, callback); 
clientRequest.end(); 
+1

const選項= { socketPath:'/tmp/static0.sock', path:'/ volumes/list', };這是我錯過的關鍵部分 –

0

請看下面的例子:

客戶端代碼: 你也可以做一些代碼插座連接:

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script> 
 
<script> 
 
    socket = io.connect('http://www.example.com' , {'force new connection':true}); 
 
    socket.on('event', function(){ 
 
    // code to execute 
 
    }); 
 
</script>

nodejs中的服務器端代碼: 對於此安裝NPM,然後 1)初始化NPM 2 )NPM安裝--save表達 3)NPM insatll --save插座

var express = require('express'); 
 
var app = express(); 
 
var http = require('http'); 
 
var server = http.createServer(); 
 
var io = require('socket.io').listen(server); 
 
var socket = null; 
 

 
io.sockets.on('connection', function(soc) { 
 
    socket = soc; 
 
    console.log('socket connected'); 
 
}); 
 

 

 
app.get('/test', function(request, response) { 
 
    var message = "Hello world"; 
 
    socket.emit('event', message); 
 
    response.writeHead(200); 
 
    reponse.write(message); 
 
    reponse.end(); 
 
}); 
 

 
var server = app.listen(8080, '0.0.0.0');

您可以從瀏覽器中點擊此一檢查