Error in AJAX request for server Node.js. (readyState: 0 and status: 0)

0

I am making the following AJAX request:

function ping(){
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "GET",
            url: "localhost:5000/ping",
            success: function(res){
                resolve(res);
            },
            error: function(res){
                reject(res);
            }
        });
    });
}

If I make a request using Postman to localhost:5000/ping it works normally, but when I do the request using AJAX I get the following message in the console:

Object { readyState: 0, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(), … }

Theapp.jsoftheAPIonnodeisasfollows:

constexpress=require('express');constbodyParser=require('body-parser');constPORT=process.env.PORT||5000app=express();(async()=>{try{app.use(bodyParser.json());app.use(bodyParser.urlencoded({extended:true}));(functionloadRoutes(){require('./src/api/routes/ping.js')(app);})();app.use(function(req,res,next){res.header('Access-Control-Allow-Origin',"*"); 
            res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE'); 
            res.header('Access-Control-Allow-Headers', 'Content-Type'); 
            next(); 
        })

        app.get('/ping', (req, res) => {
            res.status(200).json({ date: new Date() });
        });

        app.listen(PORT, () => console.log('Listening on ${ PORT }'))

    } catch (ex) {
        console.log(ex);
    }
})();

Until recently I was having problems with CORS , I enabled Access-Control-Allow-Origin in app.js and I no longer receive the CORS message, but I still have that error in return when the request is made via AJAX , if it is via Postman , it works correctly.

    
asked by anonymous 24.11.2018 / 19:04

0 answers