Estoy iniciando el servidor desde mi script y luego quiero ejecutar mis pruebas. Pero cuando inicio el servidor, el proceso de inicio del servidor no regresa, ya que se está ejecutando y el control no se devuelve. El servidor se inicia y se puede acceder a la aplicación en http://localhost:8000. así que he usado la búsqueda de nodejs y la solicitud http para verificar si la respuesta == 200 en http://localhost:8000 pero obtengo el error: console.error FetchError {mensaje: 'solicitud a http://127.0.0.1:8000/ falló, razón: conecte ECONNREFUSED 127.0.0.1:8000', escriba: 'sistema', errno: 'ECONNREFUSED', código: 'ECONNREFUSED' } ¿Hay alguna manera de que pueda sondear y comenzar mis pruebas? Mi código:
const util = require('util'); const exec = util.promisify(require('child_process').exec); const fetch = require('node-fetch'); const http = require('http'); async function waitforlocalhost() { await fetch('http://127.0.0.1:8000/'), (response) => { //http.get({hostname:'localhost',port: 8000,path: '/',method: 'GET',agent: false}, (response) => { if (response.status === 200) { resolve(); return; } else { setTimeout(waitforlocalhost,2000); } } } class CreateEnv { async Execute () { try { //create database and start server console.log("Create database and runserver..."); exec('python manage.py startserver'); await waitforlocalhost(); console.log("Server started..."); } catch (e) { console.error(e); console.log("Error creating database and runserver..."); return; } } } module.exports = CreateEnv;Reescribió su corrector de la siguiente manera,
const fetch = require('node-fetch') function waitforhost(url, interval = 1000, attempts = 10) { const sleep = ms => new Promise(r => setTimeout(r, ms)) let count = 1 return new Promise(async (resolve, reject) => { while (count < attempts) { await sleep(interval) try { const response = await fetch(url) if (response.ok) { if (response.status === 200) { resolve() break } } else { count++ } } catch { count++ console.log(`Still down, trying ${count} of ${attempts}`) } } reject(new Error(`Server is down: ${count} attempts tried`)) }) } async function main() { const url = 'http://127.0.0.1:8000/' console.log(`Checking if server is up: ${url}`) try { await waitforhost(url, 2000, 10) console.log(`Server is up: ${url}`) } catch (err) { console.log(err.message) } } main()Resultados en:
Checking if server is up: http://127.0.0.1:8000/ Still down, trying 2 of 10 Still down, trying 3 of 10 Still down, trying 4 of 10 Still down, trying 5 of 10 Still down, trying 6 of 10 Still down, trying 7 of 10 Still down, trying 8 of 10 Still down, trying 9 of 10 Still down, trying 10 of 10 Server is down: 10 attempts triedO cuando el éxito
Checking if server is up: http://127.0.0.1:8000/ Server is up: http://127.0.0.1:8000/Te dejaré implantar en tu código.