Mar*_*eri 12 javascript connect node.js
这个小程序有问题:
var http = require("http");
var request = http.request({
hostname: "localhost",
port: 8000,
path: "/",
method: "GET"
}, function(response) {
var statusCode = response.statusCode;
var headers = response.headers;
var statusLine = "HTTP/" + response.httpVersion + " " +statusCode + " " + http.STATUS_CODES[statusCode];
console.log(statusLine);
for (header in headers) {
console.log(header + ": " + headers[header]);
}
console.log();
response.setEncoding("utf8");
response.on("data", function(data) {
process.stdout.write(data);
});
response.on("end", function() {
console.log();
});
});
Run Code Online (Sandbox Code Playgroud)
控制台的结果如下:
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
我不明白为什么会这样.
Piy*_*gar 20
从您的代码中,您的文件看起来像包含向localhost(127.0.0.1:8000)发出get请求的代码.
问题可能是您没有在本地计算机上创建侦听端口8000的服务器.
为此,您必须在localhost上设置服务器,该服务器可以满足您的请求.
创建server.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Run Code Online (Sandbox Code Playgroud)运行server.js:node server.js
运行包含要发出请求的代码的文件.
Ahm*_*abi 12
请使用 [::1] 而不是 localhost,并确保端口正确,并将端口放在链接中。
const request = require('request');
let json = {
"id": id,
"filename": filename
};
let options = {
uri: "http://[::1]:8000" + constants.PATH_TO_API,
// port:443,
method: 'POST',
json: json
};
request(options, function (error, response, body) {
if (error) {
console.error("httpRequests : error " + error);
}
if (response) {
let statusCode = response.status_code;
if (callback) {
callback(body);
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79846 次 |
| 最近记录: |