SSL Error in nodejs request package - javascript

I'm trying to call freecodecamp api #url https://forum.freecodecamp.org/c/getting-a-developer-job.json?
I am doing some analysis on the data, but when I call this service using 'request' npm package I am getting ssl error as follows:
error { Error: write EPROTO 140735782093632:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1500:SSL alert number 40
140735782093632:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:659:
at _errnoException (util.js:1022:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:867:14) code: 'EPROTO', errno: 'EPROTO', syscall: 'write' }
Can somebody let me know what the issue is? A wget call pulls the data when provided with --ca-certificate option, also the webservice is giving data to postman without any certificate.
Here is my code:
import request from 'request';
import fs from 'fs';
const BASE_URL = 'forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1';
request.get(BASE_URL, {
port: 443,
agentOptions: {
ciphers: 'ALL',
ca: fs.readFileSync('./mycertfile.pem'),
secureProtocol: 'TLSv1_2_method'
},
strictSSL: false
})
.on('response', (response) => {
console.log('Response is ', response);
}).on('error', (err) => {
console.log('error', err);
});

I see no problems there except URI http:// is absent, in my environment i have node v10.5.0, and the slightly modified version of your script works well:
const request = require('request')
const BASE_URL = 'https://forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1'
request.get(BASE_URL, { json: true }, (err, res, body) => {
if (err) throw('error', err);
console.log('JSON object is => ', body);
})
outputs to console:
JSON object is => { users:
[ { id: 117390,
username: 'anthony2025',
....

Related

NodeJS Error when sending POST request using http.request or Axios

I'm trying to send some data in NodeJS from one localhost server to another, but I'm getting a nasty error. On the server that receives the request it appears the request goes through because I'm getting an object logged to the terminal there, except its properties are null (they're supposed to be set to the properties in the req body, or null).
I get the error even if I try with Axios, which tells me that it’s not an issue with http.request or Axios. If anyone could help me understand what's going on I'd appreciate it.
Error:
events.js:377
throw er; // Unhandled 'error' event
^
Error: write EPROTO 8669511168:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:
at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16)
Emitted 'error' event on ClientRequest instance
{
errno: -100,
code: 'EPROTO',
syscall: 'write'
}
The project sending the request looks like this:
Resources file
const http = require('http');
const options = {
host: 'localhost',
port: 3000,
path: '/create',
method: 'POST',
header: {
'Content-Type':'application/json'
}
}
const body = {
inquiryTotal: ‘20.00’
}
const stringifiedBody = JSON.stringify(body)
module.exports.Inquiries = {
create: () => {
req = http.request(options, (res) => {
console.log(res);
});
req.write(stringifiedBody); // this is an object that's already stringified to JSON
req.end();
/*axios.post('localhost:3000/v1/orders/create', {
orderTotal: '21.00'
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})*/
}
}
Server sending request:
const resource = require('./lib/resource');
// create server code
resource.Inquiries.create;
Assuming you are correctly setup your API endpoint, you can try this (added some comments inside the code):
const axios = require("axios").default;
const body = {
inquiryTotal: "20.00" // Use single-qupte ('') or double-quote ("") here and don't use back-quote (``)
};
module.exports.Inquiries = {
create: () => {
axios
.post("http://localhost:3000/v1/orders/create", body) // Add http:// in the beginning of your url
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}
};

auth0 Management Api NextJs not able to update metadata

Really struggling to get my head around authO management clients so I can update users information. I've created a Next.js API route for the backend but I'm not sure how to actually amend the user's data. I've followed the docs and got to the point below.
API route
The ID params I manually entered to test and my response is an empty JSON object.
The docs don't make it clear what I'm suppose to do in the update user area in.
var ManagementClient = require("auth0").ManagementClient;
export default async (req, res) => {
var auth0 = new ManagementClient({
domain: process.env.AUTH0_BASE_URL,
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
scope: "read:users update:users",
});
var params = { id: "**************************" };
var metadata = {
foo: "bar",
};
auth0.users.updateAppMetadata(params, metadata, function (err, user) {
if (err) {
// Handle error.
}
// Updated user.
console.log(user);
res.status(200).json({ user });
});
};
Error:
API resolved without sending a response for /api/authapi, this may result in stalled requests.
SanitizedError [APIError]: getaddrinfo ENOTFOUND http
(node:internal/process/task_queues:81:21) {
statusCode: 'ENOTFOUND',
requestInfo: { method: 'post', url: '***********' },
originalError: Error: getaddrinfo ENOTFOUND http
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http',
response: undefined
}
}

my express endpoint route with mysql logs an error: connect ECONNREFUSED 127.0.0.1

I'm building a web app for a bootcamp. I'm using express and mysql. I'm routing a get request to an endpoint. The route should query my mysql database table to select all. I'm expecting to send the result to the chrome page. Instead I get this error:
Error: connect ECONNREFUSED 127.0.0.1:8211
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1054:14)
--------------------
at Protocol._enqueue (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:119:18)
at Connection._implyConnect (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:457:10)
at Connection.query (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:199:8)
at Object.getAllUsers (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/database/index.js:17:14)
at /Users/cnebs/Documents/HRATX/hratx42-fullstack-review/server/index.js:22:6
at Layer.handle [as handle_request] (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/route.js:112:3) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8211,
fatal: true
}
I'm able to query the database in terminal. I'm able to send text to the page on chrome through express. I've built a database and table. I haven't used the api for my project to populate the table yet. My console is logging the error through a function in my database index which I've imported to express to be used in the get route.
Here is the database index:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "password",
database: "github",
port: 8211
});
const test = () => {
connection.query("DESCRIBE git_repos", (err, res) => {
console.log('selection: ', res)
})
}
const getAllUsers = cb => {
connection.query(`select * from todos`, (err, res) => {
if (err) {
console.log("error in getAllUsers: ", err);
cb(err);
} else {
cb(null, res);
}
});
}
module.exports = { test, getAllUsers }
Here is the server index:
const express = require('express');
const db = require('../database')
let app = express();
app.use(express.static(__dirname + '/../client/dist'));
app.get('/repos', function (req, res) {
// TODO - your code here!
// This route should send back the top 25 repos
db.getAllUsers((err, result) => {
if (err) {
console.error(err)
res.status(404).end();
} else {
console.log('Getting')
res.send(result)
}
})
});
let port = 1128;
app.listen(port, function() {
console.log(`listening on port ${port}`);
});
I expect to see any result at all from my query delivered to the page from the res.send.
Instead, I see that the localhost page can't be found and the err response above in my server terminal.
You aren't able to directly choose the port for your database server in the createConnection(). Remove the port property and it will function.

How to fix MaxListenersExceededWarning error?

In my Node.js http web server I use ssh2-sftp-client library to load csv files from remote SFTP server. It raise error when user try to load several files and I don't understand how to fix it?
CODE:
router.post('/', (req, res) => {
const fileName = req.body.file_name
const remotePath = '/reports/' + fileName
const localePath = path.join(process.env.HOME || process.env.USERPROFILE, 'Downloads/' + fileName)
sftp.connect(config.sftpServer, 'on').then(() => {
sftp.fastGet(remotePath, localePath, {}).then(() => {
res.header('Content-type', 'text/csv; charset=windows-1251')
res.sendFile(localePath)
sftp.end()
}).catch((err) => {
sftp.end()
console.log(err, 'fastGet method error')
})
}).catch((err) => {
sftp.end()
console.log(err, 'connect method error')
})
})
ERROR:
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Finally I found the problem. Instead of on method you need to use once method.
sftp.connect(config.sftpServer, 'once').then(() => {
// CODE
}

How to make gun accept a self-signed certificate?

gun 0.8.8, Node.js-to-Node.js, Node.js-to-browser
I see the following error in browser console:
VM103:161 WebSocket connection to 'wss://127.0.0.1:8080/gun' failed: Error in connection establishment: net::ERR_INSECURE_RESPONSE
VM103:161 WebSocket connection to 'wss://10.42.0.56:8080/gun' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
And there are no messages on Node.js side.
Sorce code of my server:
const Hapi = require('hapi');
const Gun = require('gun');
const pem = require('pem');
pem.createCertificate({ days: 1, selfSigned: true }, function (err, keys) {
if (err) {
throw err
}
const server = new Hapi.Server;
var tls = {
key: keys.serviceKey,
cert: keys.certificate
};
server.connection({
port: 8080,
tls
});
server.connections.forEach(c => Gun({ web: c.listener, file: 'data.json' }));
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Server works!');
}
});
server.start();
})
In order to make gun work with a self-signed certificate you need two things:
Lunch browser ignoring the certificate errors. For example, Chrome
google-chrome --ignore-certificate-errors
Put the following process option in Node.js code
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
or add the environment variable
export NODE_TLS_REJECT_UNAUTHORIZED=0

Categories

Resources