Http.request在node.js中

这是我在节点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); }); 

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

在这里input图像说明

编辑:随着快递的作品,但如果我想使它不工作,我怎么办?

testing这个:

 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上监听。你的问题在服务器端,而不是在客户端。 特别是,您尝试连接到的服务器不在本地主机上的端口8124上进行侦听 – 至less不在此主机上。

要解决这个问题,只要添加到前面的代码即服务器代码即可。

 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)