问题
I am new to the node.js. I am trying to setup the client server connection using unix socket, where my client request would be in node.js and server running in the background would be in go.
Client side Code:
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)
}
}
})
When I try to communicate with the server written in go it is shows the HTTP error: 400 Bad Request: malformed Host header'
The same works with:
curl -X GET --unix-socket /tmp/static0.sock http://:/volumes/list
Not sure what is wrong with my request. Do we need to send the headers? I expecting the JSON response.
回答1:
To accomplish this without using the request module, try the following:
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();
回答2:
Consider the following example :
client side code : Also you can do socket connection in some code :
<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>
server side code in nodejs : For this install npm, then 1)npm init 2)npm install --save express 3)npm insatll --save socket
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');
You can hit this from browser a check
来源:https://stackoverflow.com/questions/41177350/node-js-send-get-request-via-unix-socket