Puppeteer on Raspberry Pi fails to start chromium-browser: Error: read ECONNRESET - raspberry-pi

I am trying to run puppeteer on a Raspberry Pi 4 with Ubuntu installed.
const puppeteer = require('puppeteer');
async function configureBrowser() {
// error here
var browser1 = await puppeteer.launch({ headless: true, executablePath: '/usr/bin/chromium-browser', args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
await page.goto('www.google.com');
return page;
}
async function monitor() {
let page = await configureBrowser();
}
monitor().catch(error => { console.error("Something bad happened...", error); });
It produces the error below from the chromium-browser. Does anyone know what this means? I have tried installing extra dependencies and various options for the browser launch, but nothing yet works. It is a Raspberry Pi 4 that I ssh into.
(node:2870) ExperimentalWarning: The fs.promises API is experimental
Something bad happened... ErrorEvent {
target:
WebSocket {
_events:
[Object: null prototype] { open: [Function], error: [Function] },
_eventsCount: 2,
_maxListeners: undefined,
_binaryType: 'nodebuffer',
_closeCode: 1006,
_closeFrameReceived: false,
_closeFrameSent: false,
_closeMessage: '',
_closeTimer: null,
_extensions: {},
_protocol: '',
_readyState: 3,
_receiver: null,
_sender: null,
_socket: null,
_bufferedAmount: 0,
_isServer: false,
_redirects: 0,
_url:
'ws://127.0.0.1:35593/devtools/browser/b4694718-7829-4f29-945a-1a16d20455a8',
_req: null },
type: 'error',
message: 'read ECONNRESET',
error:
{ Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) errno: 'ECONNRESET', code: 'ECONNRESET', syscall: 'read' } }

Related

Can't connect to mongoose/mongodb

When I'm trying to add an item to my database I get the following error on the terminal:
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\connection.js:825:32)
at C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:417:10
at C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:1270:10)
at Mongoose.connect (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:416:20)
at Object.<anonymous> (C:\Users\88cro\Desktop\blog\server.js:6:10)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 162133351,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\88cro\Desktop\blog\node_modules\mongodb\lib\cmap\connect.js:387:20)
at Socket.<anonymous> (C:\Users\88cro\Desktop\blog\node_modules\mongodb\lib\cmap\connect.js:310:22)
at Object.onceWrapper (node:events:628:26)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1284:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
Node.js v19.0.1
[nodemon] app crashed - waiting for file changes before starting...
I have MongoDB Atlas and mongoshell installed and running but that doesn't seem to fix the problem.
This is how I setup express and mongoose, I tried to change the url in mongoose.connect but it doesn't seem to work
const express = require('express')
const mongoose = require('mongoose')
const articleRouter = require('./routes/articles')
const app = express()
mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true})
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.get('/', (req, res) => {
const articles = [{
title: 'Test title',
createdAt: new Date(),
description: 'Test description'
}]
res.render('articles/index', { articles: articles })
})
app.use('/articles', articleRouter)
app.listen(5000)
Any ideas about how to fix this? Thanks!

how to fix the error no. -4078, in mongoose connection to the server what's cause this?

What is wrong with this setup
'''
nodejs
'''
require('dotenv').config()
// console.log(process.env)
const express = require('express')
const app = express()
const expressLayouts = require("express-ejs-layouts")
const indexRouter = require('./routes/index')
const mongoose = require('mongoose');
app.set("view engine", "ejs")
app.set("views", __dirname + "/views")
app.set('layout', "layouts/layout")
app.use(expressLayouts)
app.use(express.static('public'))
app.use('/', indexRouter)
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://localhost:27017/printshop',{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
const db = mongoose.connection
db.on('error', error=> console.log(error))
db.once('open', ()=> console.log('connected to mongogoose'))
app.listen(process.env.PORT)
im trying to connect to mongodb in my local network but suddenly this
error message
just out
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (E:\nodejs\node-server\node_modules\mongoose\lib\connection.js:825:32)
at E:\nodejs\node-server\node_modules\mongoose\lib\index.js:417:10
at E:\nodejs\node-server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (E:\nodejs\node-server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (E:\nodejs\node-server\node_modules\mongoose\lib\index.js:1270:10)
at Mongoose.connect (E:\nodejs\node-server\node_modules\mongoose\lib\index.js:416:20)
at Object.<anonymous> (E:\nodejs\node-server\server.js:20:10)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1166:10) {
reason: TopologyDescription {
queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
what the mean?
im looking for the log of "connected to mongogoose" but it doesnt show in console then the error comes
ECONNREFUSED ::1:27017
what is this mean?
if anyone had a problem like this you can fix it by changing the
mongoodb://localhost/
to
mongoodb://127.0.0.1/

Nuxt.js socket hang up on axios get only on https not http server

I'm using Nuxt 2.8.1, Axios Module (https://axios.nuxtjs.org).
I followed up this guide https://nuxtjs.org/faq/http-proxy/ to solve CORS problems on Firefox/IE, but ended up NuxtServerError: socket hang up on every proxied request if I ENABLE server https option in nuxt.config.js, not if I disable.
I tried adding rejectUnauthorized: false to server https param, wrote an express server to handle the SSL certificate and render using Nuxt,... but still can't solve the problem.
This is my nuxt.config.js:
env: {
API_HOST: 'https://api.mywebsite.com',
BASE_URL: process.env.BASE_URL || 'http://localhost:3000',
},
axios: {
proxy: true,
},
proxy: {
'/api/': {
target: 'https://api.mywebsite.com/api',
pathRewrite: {'/api': ''},
credentials: false,
}
},
server: {
port: 3000,
https: {
rejectUnauthorized: false,
key: fs.readFileSync('../privkey.pem'),
cert: fs.readFileSync('../fullchain.pem')
}
}
It works well if i just remove whole https param in 'server'. Here is my axios call on store/index.js:
export const actions = {
async nuxtServerInit ( { commit } ) {
const { data } = await this.$axios.get('/api/option');
let options = {};
data.forEach(item => {
options[item.Name] = item.Value;
});
commit('setOptions', options)
},
}
This is my console log on that axios call:
Promise { 18:04:38
<rejected> [Error: socket hang up] {
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at Socket.EventEmitter.emit (domain.js:448:20)
at endReadableNT (_stream_readable.js:1129:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
code: 'ECONNRESET',
config: {
url: 'http://localhost:3000/api/option',
method: 'get',
headers: [Object],
baseURL: 'http://localhost:3000/',
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
request: Writable {
_writableState: [WritableState],
writable: true,
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://localhost:3000/api/option'
},
response: undefined,
isAxiosError: true,
toJSON: [Function]
}
}
I would appreciate any help :)
I tried to use as many options as I thought was relevant in the proxy module, but ended up nowhere. I think you should create an issue on either #nuxtjs/proxy or on http-proxy-middleware github.
On my end the proxy route works without a problem with Vue's normal lifecycles, but will end up with a socket hang up when placed in asyncData or fetch - so I assume it's a SSR issue.
I don't have any problems with CORS, so I ended up creating module clones of the axios-module with custom prototypes. This setup unfortunately doesn't work alongside the axios-module as that also creates a socket hangup regardless of whether I have a proxy setup.
https://stackoverflow.com/a/43439886/1989083
I fixed my same issue by adding these lines into axios.js:
delete process.env['http_proxy'];
delete process.env['HTTP_PROXY'];
delete process.env['https_proxy'];
delete process.env['HTTPS_PROXY'];

Can make post request to localhost using node-fetch, but unable to do so using Axios

I have tried making the same post request using node-fetch and axios.
var fetch = require('node-fetch');
var axios = require('axios');
async function fetchTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const streamResponse = await fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
const jsonResponse = await streamResponse.json()
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function axiosTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const jsonResponse = await axios({
method: 'post',
url: `${host}:${port}`,
data: body
})
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function test() {
console.log(await fetchTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
console.log(await axiosTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
}
test();
The request made with node-fetch works nicely. The request made with axios returns (IP address redacted with ...) an error:
{ successMessage: '',
errorMessage:
{ Error: connect ECONNREFUSED ...:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '...',
port: 80,
config:
{ adapter: [Function: httpAdapter],
transformRequest: [Object],
transformResponse: [Object],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'http://127.0.0.1:8801',
data: '{"type":"request","cmd":"devices"}' },
request:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 39,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://.../',
_isRedirect: true },
response: undefined } }
What might be the reason? Am I doing something wrong?
EDITED with more info requested in comment:
The axios request fails the same way if I comment out the node-fetch request.
The node-fetch request returns:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response' },
}
Since I wrap the result in a response object, the console.log looks like
{
successMessage:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response'
},
errorMessage: ''
}

how can I get other db instance in nodejs 3.0 mongo-client?

I used mongo-nodejs 2.2 and upgraded to 3.0. After upgrading, I found that the method db() in Db class doesn't exist anymore (http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html). This method is very useful to switch to different database instance. I wonder how I can switch to different database with the latest version.
Okay so it is gone, and it's documented as gone and the real message is you should be using Mongoclient.prototype.db instead:
From the 3.0 Changes:
We removed the following API methods.
Db.prototype.authenticate
Db.prototype.logout
Db.prototype.open
Db.prototype.db
...
We've added the following API methods.
MongoClient.prototype.logout
MongoClient.prototype.isConnected
MongoClient.prototype.db
The basic lesson here was wherever you were using Db directly, you should be using the MongoClient instance instead. This is obtained from the very first connection:
const { MongoClient } = require('mongodb');
(async function() {
try {
const conn = await MongoClient.connect('mongodb://localhost');
let test = conn.db('test');
let admin = test.admin();
console.log(admin);
let another = conn.db('another');
console.log(another);
} catch(e) {
console.error(e);
} finally {
process.exit();
}
})()
Returns output like:
Admin {
s:
{ db:
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
promiseLibrary: [Function: Promise] } }
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ databaseName: 'another',
dbCache: {},
children: [],
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
options:
{ readPreference: [Object],
promiseLibrary: [Function: Promise] },
logger: Logger { className: 'Db' },
bson: BSON {},
readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] }
Interestingly the admin() helper still exists on Db instances, which of course is really just a "pre filled" selection to the old db() anyway.
Bottom line, use the MongoClient instance from the connection instead for all future code.