Reputation: 301
I'm trying to start a web server and test the http request/response in one node.js file.
The server is running and I can open it in my browser with ip 'http://127.0.0.1:8080'.
Also I can run 'curl http://127.0.0.1:8080' in the terminal and get response.
However, when I tried to run my js script, the output showed the connection was denied. Why is it happen and how can I resolve this issue?
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())
}
The output from the curl execution in the js file is:
Failed to connect to 127.0.0.1 port 8080: Connection refused
This is the output from '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
Upvotes: 0
Views: 4402
Reputation: 301
I found the problem is when I started the server in my code, it immediately executed 'curl'. In the meantime the server had not been started yet. Therefore I got such connection denied error.
I tried to setTimeout on 'curl' for 5 seconds and the cmd successfully gave me the http response.
However I think the code looks ugly. Is there a better way to write?
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);
Upvotes: 0
Reputation: 4533
Try with 0.0.0.0 insted of 127.0.0.1 This is work for both either localhost and by ip also.
Upvotes: 2