1

这是我在节点 js 中的代码:

var http = require('http');

var options = { 
    host : '127.0.0.1',
    port: 8124,
    path: '/',
    method: 'GET'
};

http.request(options, function(res){    
    console.log("Hello!");  
}).end();

process.on('uncaughtException', function(err){  
    console.log(err);
});

当我编译它时,编译器向我显示以下错误:

在此处输入图像描述

编辑:使用快递,但如果我想让它在没有快递的情况下工作,我该怎么办?

4

2 回答 2

1

测试这个:

const app = require('express')();
app.get('/', (req, res) => {
  res.json({ ok: true });
});
app.listen(8124);

var http = require('http');

var options = {
    host : '127.0.0.1',
    port: 8124,
    path: '/',
    method: 'GET'
};

http.request(options, function(res){
    console.log("Hello!");
}).end();

process.on('uncaughtException', function(err){
    console.log(err);
});

如您所见,它会打印Hello!- 当端口 8124 上正在侦听某些内容时。您的问题出在服务器端,而不是客户端。具体来说,您尝试连接的服务器未在 localhost 上的端口 8124 上侦听 - 至少不在此主机上。

于 2017-07-06T12:54:02.620 回答
0

为了解决这个问题,添加到前面的代码中就足够了,服务器代码。

var http = require('http');

var options = { 
    host : '127.0.0.1',
    port: 8124,
    path: '/',
    method: 'GET'
};

http.request(options, function(res){    
    console.log("Hello!");  
}).end();

process.on('uncaughtException', function(err){  
    console.log(err);
});

http.createServer((req, res)=>{ 
    res.writeHead(200, {'Content-type': 'text/plain'})
    res.end()   
}).listen(8124)
于 2017-08-23T12:55:21.593 回答