Search code examples
javascriptnode.jsexpressterminalnode-fetch

Running a node.js program that makes a fetch call to an express server running on my local machine


How do I run a javascript program in node.js that makes a local fetch call to a server running on my local machine?

I have a local express server that is listening on port 4001:

const express = require('express');
const app = express();  

const PORT = process.env.PORT || 4001;

app.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
})

app.use('/test', (req, res, next) => {
    res.send('test');
})

I have a separate app.js file that makes a node-fetch call to this server:

const fetch = require('node-fetch');

const payload = fetch('https://localhost:4001/test');

payload.then(response => response.json())
.then(jsonResponse => {
    console.log(jsonResponse);
}).catch(error => {
    console.log(error);
})

Running node app.js in terminal resulted in the following error message:

FetchError: request to https://localhost:4001/test failed, reason: write EPROTO
15088:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\dep
s\openssl\openssl\ssl\record\ssl3_record.c:332:

    at ClientRequest.<anonymous> (C:\Users\lowys\projects\dump\node-test\node_mo
dules\node-fetch\lib\index.js:1455:11)
    at ClientRequest.emit (events.js:210:5)
    at TLSSocket.socketErrorListener (_http_client.js:406:9)
    at TLSSocket.emit (events.js:210:5)
    at errorOrDestroy (internal/streams/destroy.js:108:12)
    at onwriteError (_stream_writable.js:452:5)
    at onwrite (_stream_writable.js:473:5)
    at internal/streams/destroy.js:50:7
    at TLSSocket.Socket._destroy (net.js:664:5)
    at TLSSocket.destroy (internal/streams/destroy.js:38:8) {
  message: 'request to https://localhost:4001/test failed, reason: write EPROTO
15088:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\\ws\\d
eps\\openssl\\openssl\\ssl\\record\\ssl3_record.c:332:\n',
  type: 'system',
  errno: 'EPROTO',
  code: 'EPROTO'
}

Solution

  • Based on the protocol (EPROTO) error, try targeting http instead of https given its localhost:

    const fetch = require('node-fetch');
    
    const payload = fetch('http://localhost:4001/test');
    
    payload.then(response => response.json())
    .then(jsonResponse => {
        console.log(jsonResponse);
    }).catch(error => {
        console.log(error);
    })
    

    That is unless you created some sort of root SSL certificate and added the certificate to your machine.