node.js http请求获得连接被拒绝错误

时间:2019-01-22 00:29:43

标签: node.js

我正在尝试启动Web服务器并在一个node.js文件中测试http请求/响应。

服务器正在运行,我可以在浏览器中使用ip'http://127.0.0.1:8080'打开它。

我还可以在终端中运行'curl http://127.0.0.1:8080'并获得响应。

但是,当我尝试运行js脚本时,输出显示连接被拒绝。为什么会发生,如何解决此问题?

const { exec } = require('child_process');

const testDirectory = 'testDirectory';
const demoDirectory = 'packages/my-react-component';

console.log('start server');
yarnRun = exec('yarn run start:demo', {
    cwd: process.cwd().toString() + '/' + testDirectory + '/' + demoDirectory + '/',
});
process.stdin.resume(); // I want my server keep alive

const localhost = 'http://127.0.0.1:8080';
getRequestTest = exec('curl ' + localhost);
getRequestTest.stdout.on('data', function(data)){
    console.log('stdout: ', data.toString())
}
getRequestTest.stderr.on('data', function(data)){
    console.log('stderr: ', data.toString())
}

js文件中curl执行的输出是:

Failed to connect to 127.0.0.1 port 8080: Connection refused

这是'curl http://127.0.0.1:8080 -v'的输出

stderr: * Rebuilt URL to: http://127.0.0.1:8080/

stderr:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
stderr: *   Trying 127.0.0.1...
* TCP_NODELAY set

stderr: * Connection failed
* connect to 127.0.0.1 port 8080 failed: Connection refused
* Failed to connect to 127.0.0.1 port 8080: Connection refused
* Closing connection 0
curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused

2 个答案:

答案 0 :(得分:0)

尝试将0.0.0.0安装为127.0.0.1,这对于localhost和ip均适用。

答案 1 :(得分:0)

我发现问题是当我用代码启动服务器时,它立即执行了“ curl”。同时,服务器尚未启动。因此我得到了这样的连接被拒绝错误。

我试图在'curl'上设置setTimeout 5秒钟,cmd成功给了我http响应。

但是我认为代码看起来很难看。有没有更好的书写方式?

startServer = exec('node ' + process.cwd().toString() + '/script/startServer.js');

const localhost = 'http://127.0.0.1:8080';
console.log('localhost: ' + localhost);

function testRequest() {
    console.log('run curl ' + localhost + ' -v');
    getRequestTest = exec('curl ' + localhost + ' -v');
    getRequestTest.stdout.on('data', function(data) {
        console.log('stdout: ' + data.toString());
    });
    getRequestTest.stderr.on('data', function(data) {
        console.log('stderr: ' + data.toString());
    });
}

setTimeout(testRequest, 5000);
相关问题