error: (-215) !empty() in function detectMultiScale in Opencv.JS - javascript

I have checked and tried these solutions here but none is helping
error: (-215) !empty() in function detectMultiScale
OpenCV.js - detectMultiScale "This Exception cannot be caught"
I also read elsewhere that the problem could be because the file needs to be served via an Http request and so I decided to use ngrok but I still found the same error. Currently am using python http.server
Here is the section of the code:
let classifier = new cv.CascadeClassifier();
let utils = new Utils('errorMessage'); //use utils class
let faceCascadeFile = "http://localhost:8000/docs/haarcascade_frontalface_default.xml";
//let faceCascadeFile = "D:\Code\Fit-to-Interact-web\docs\haarcascade_frontalface_default.xml"
//let faceCascadeFile = "https://0979da552cb5.ngrok.io/docs/haarcascade_frontalface_default.xml"; // path to xml
// use createFileFromUrl to "pre-build" the xml
//Make sure to run it in a webserver because it has to do XMLHTTPRequests.
utils.createFileFromUrl(faceCascadeFile, faceCascadeFile, () => {
classifier.load(faceCascadeFile); // in the callback, load the cascade from file
});
console.log(classifier.empty())
Worse when I use the absolute/relative file path I get this error Not allowed to load local resource or sometimes the same error:
Exception: OpenCV(4.4.0) /build/master-contrib_docs-lin64/opencv/modules/objdetect/src/cascadedetect.cpp:1689:
error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

Related

Trying to use AXIOS for get request, error "require is not defined" [duplicate]

This question already has answers here:
Client on Node.js: Uncaught ReferenceError: require is not defined
(11 answers)
Closed 11 months ago.
My code is below. This is my first time using NodeJS and axios.
I have installed NodeJS on Windows using the downloadable installer. I then installed Axios using npm install axios in powershell as admin.
I'm obviously copy/pasting the boilerplate nodejs code for an axios get request.
I've tested the php file using a curl get request from command line (installed actual curl, not the windows shortcut to another program.) So the PHP is accepting get requests and serving json back properly.
The issue I'm stuck on is how to setup axios and node js properly so that my js file runs the get request properly.
This is my code
const loginForm = document.getElementById("login-form");
const loginButton = document.getElementById("login-form-submit");
const loginErrorMsg = document.getElementById("login-error-msg");
const vanillaUrl = "localhost:8081/hospital/php/addapt.php";
const getUrl = "localhost:8081/hospital/php/getpatientappt.php?PatientID=1";
const axios = require('axios')
//get request to get appt for patient id1
axios
.get(geturl)
.then(res => {
console.log(`statusCode: ${res.status}`)
console.log(res)
alert(res)
})
.catch(error => {
console.error(error)
})
loginButton.addEventListener("click", (e) => {
e.preventDefault();
const username = loginForm.username.value;
const password = loginForm.password.value;
if (username === "user" && password === "1") {
alert("You logged in!");
location.reload();
} else {
loginErrorMsg.style.opacity = 1;
}
}
)
These are the errors I'm getting in chrome from the javascript console
Uncaught ReferenceError: require is not defined
at login-page.js:7:15
DevTools failed to load source map: Could not load content for chrome-extension://hnfanknocfeofbddgcijnmhnfnkdnaad/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
DevTools failed to load source map: Could not load content for http://localhost:8081/hospital/login/requestProvider.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
When I run incognito I get
Uncaught ReferenceError: require is not defined
at login-page.js:7:15
there is no file requestProvider.js.map or content.js.map
This is all being hosted on localhost with xampp. I'm not sure if that affects anything.
I'm not sure what this error is. Got stuck googling it. And I'm not sure how to integrate this code properly.
seems like you're running this code in browser, browser implementation of Javascript doesn't have require function

Node.js 'fs' throws an ENOENT error after adding auto-generated Swagger server code

Preamble
To start off, I'm not a developer; I'm just an analyst / product owner with time on their hands. While my team's actual developers have been busy finishing off projects before year-end I've been attempting to put together a very basic API server in Node.js for something we will look at next year.
I used Swagger to build an API spec and then used the Swagger code generator to get a basic Node.js server. The full code is near the bottom of this question.
The Problem
I'm coming across an issue when writing out to a log file using the fs module. I know that the ENOENT error is usually down to just specifying a path incorrectly, but the behaviour doesn't occur when I comment out the Swagger portion of the automatically generated code. (I took the logging code directly out of another tool I built in Node.js, so I'm fairly confident in that portion at least...)
When executing npm start, a few debugging items write to the console:
"Node Server Starting......
Current Directory:/mnt/c/Users/USER/Repositories/PROJECT/api
Trying to log data now!
Mock mode: disabled
PostgreSQL Pool created successfully
Your server is listening on port 3100 (http://localhost:3100)
Swagger-ui is available on http://localhost:3100/docs"
but then fs throws an ENOENT error:
events.js:174
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open '../logs/logEvents2021-12-24.log'
Emitted 'error' event at:
at lazyFs.open (internal/fs/streams.js:277:12)
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
Investigating
Now normally, from what I understand, this would just mean I've got the paths wrong. However, the file has actually been created and the first line of the log file has been written just fine
My next thought was that I must've set the fs flags incorrectly, but it was set to 'a' for append:
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
Removing Swagger Code
Now here's the weird bit: if I remove the Swagger code, the log files write out just fine and I don't get the fs exception!
This is the specific Swagger code:
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
When I comment out this code, the log file writes out just fine.
The only thing I can think that might be happening is that somehow Swagger is modifying (?) the app's working directory so that fs no longer finds the same file?
Full Code
'use strict';
var path = require('path');
var fs = require('fs');
var http = require('http');
var oas3Tools = require('oas3-tools');
var serverPort = 3100;
// I am specifically tried using path.join that I found when investigating this issue, and referencing the app path, but to no avail
const __logdir = path.join(__dirname,'./logs');
//These are date and time functions I use to add timestamps to the logs
function dateNow(){
var dateNow = new Date().toISOString().slice(0,10).toString();
return dateNow
}
function rightNow(){
var timeNow = new Date().toTimeString().slice(0,8).toString();
return "["+timeNow+"] "
};
console.info("Node Server Starting......");
console.info("Current Directory: " + __dirname)
// Here I create the WriteStreams
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
var errorsFile = fs.createWriteStream(__logdir+"/errorEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Error Log File to location: %s \nWith error description: %s',__logdir, err);
});
// And create an additional console to write data out:
const Console = require('console').Console;
var logOut = new Console(logsFile,errorsFile);
console.info("Trying to log data now!") // Debugging logging
logOut.log("========== Server Startup Initiated ==========");
logOut.log(rightNow() + "Server Directory: "+ __dirname);
logOut.log(rightNow() + "Logs directory: "+__logdir);
// Here is the Swagger portion that seems to create the behaviour.
// It is unedited from the Swagger Code-Gen tool
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
In case it helps, this is the project's file structure . I am running this project within a WSL instance in VSCode on Windows, same as I have with other projects using fs.
Is anyone able to help me understand why fs can write the first log line but then break once the Swagger code gets going? Have I done something incredibly stupid?
Appreciate the help, thanks!
Edit: Tried to fix broken images.
Found the problem with some help from a friend. The issue boiled down to a lack of understanding of how the Swagger module works in the background, so this will likely be eye-rollingly obvious to most, but keeping this post around in case anyone else comes across this down the line.
So it seems that as part of the Swagger initialisation, any scripts within the utils folder will also be executed. I would not have picked up on this if it wasn't pointed out to me that in the middle of the console output there was a reference to some PostgreSQL code, even though I had taken all reference to it out of the main index.js file.
That's when I realised that the error wasn't actually being generated from the code posted above: it was being thrown from to that folder.
So I guess the answer is don't add stuff to the utils folder, but if you do, always add a bunch of console logging...

TypeError: key must be a string, a buffer or an object at typeError with GCP file exists

I'm trying to simply test for an existence of a file on our Google Cloud Platform (GCP) storage. I'm using GCP buckets on express js servers. Below is essentially a very simple exampled copied off of https://googleapis.dev/nodejs/storage/latest/File.html#exists
EDIT: This is how I authenticate the GCP key:
const { Storage } = require('#google-cloud/storage');
const storage = new Storage({
projectId: 'my-cloud',
keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS,
});
const bucketName = 'my-ci';
(With small changes, I realise you are supposed to return data[0])
const bucket = storage.bucket(bucketName);
const file = bucket.file(path);
const exists = await file.exists().then(data => {
return data
})
But when I try run this, I get the error:
[nodemon] starting `node --inspect server/server.js`
Debugger listening on ws://127.0.0.1:9229/9a677766-4a93-4499-b57c-55f5f05096d7
For help, see: https://nodejs.org/en/docs/inspector
Server listening on port 4000!
/opt/node_modules/jwa/index.js:115
return new TypeError(errMsg);
^
TypeError: key must be a string, a buffer or an object
at typeError (/opt/node_modules/jwa/index.js:115:10)
at checkIsPrivateKey (/opt/node_modules/jwa/index.js:61:9)
at Object.sign (/opt/node_modules/jwa/index.js:147:5)
at Object.jwsSign [as sign] (/opt/node_modules/jws/lib/sign-stream.js:32:24)
at JWTAccess.getRequestHeaders (/opt/node_modules/google-auth-library/build/src/auth/jwtaccess.js:87:31)
at JWT.getRequestMetadataAsync (/opt/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:51)
at JWT.getRequestHeaders (/opt/node_modules/google-auth-library/build/src/auth/oauth2client.js:238:37)
at GoogleAuth.authorizeRequest (/opt/node_modules/google-auth-library/build/src/auth/googleauth.js:593:38)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Since the error message did not give a useful traceback, I did some digging on my own. Through putting console.log statements everywhere, I narrowed it down to the line
const exists = await file.exists().then(data => {
return data
})
and tried various approaches from removing the .then(...) clause, to removing the await (which, does work until the promise is resolved). None of these seemed to have worked.
What may be potential causes of this?
Eventually figured it out - it was due to the GCP key being an older version of the key. If you get an error like above, try to check that your key is correct.

ModuleParse Failed or Not Found

I am building a web app that allows users to type in phone numbers and send text messages via the Twilio API. I've built the functionality in a file, shown below. If I cd to this file and run node twilioActions.js, the text message gets sent.
var client = require('twilio')(CLIENT_ID, CLIENT_SECRET);
// ideally, I'd like to send the message using this method and call this from other JavaScript files
export const sendMessage = () => {
}
// the following code works when I run 'node twilioActions.js'
client.sendMessage({
to:'...',
from: '...',
body: 'Text message test.'
}, function(err, responseData) {
if (!err) {
console.log(responseData.from); // outputs "+14506667788"
console.log(responseData.body); // outputs "word to your mother."
}
});
However, I want to call the sendMessage method from a different React file. Here is it:
import * as twilioActions from './twilioActions';
class PhoneView extends React.Component{
// other methods are hidden obviously, the one below is called when a button is pressed to send a message.
sendMessage() {
twilioActions.sendMessage();
}
}
When I try to build the project, I get the following errors:
ERROR in ./~/twilio/package.json
Module parse failed:/Users/Felix/Desktop/ECE590/node_modules/twilio/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "_args": [
| [
| "twilio",
# ./~/twilio/lib/Client.js 5:17-43
ERROR in ./~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Felix/Desktop/ECE590/node_modules/request/lib
# ./~/request/lib/har.js 3:9-22
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'net' in /Users/Felix/Desktop/ECE590/node_modules/tunnel-agent
# ./~/tunnel-agent/index.js 3:10-24
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in /Users/Felix/Desktop/ECE590/node_modules/tunnel-agent
# ./~/tunnel-agent/index.js 4:10-24
I feel like I am making a simple mistake and perhaps am not using the correct libraries or including the proper references. Could someone point me in the right direction about how to get this to work? Thank you so much!
Twilio developer evangelist here.
The twilio npm module is not built or recommended for use in the front end. The main thing is that you would need to expose your account credentials in the front end code of your site. This is a security risk as it means a malicious attacker could get hold of your credentials and abuse your Twilio account.
I recommend creating a service on your server side that you can call to with an AJAX request in order to perform actions like this.

Node.js - HTTPS PFX Error: Unable to load BIO

I'm trying to make a HTTPS request-promise. I already know that the PFX is good and that is not the issue (I have a similar sample app working).
I am doing the following:
var request = require('request-promise');
...
options.pfx = fs.readFileSync('myfile.pfx');
options.passphrase = 'passphrase';
I am passing my options into an request.
request.post(options);
I then try to build the request I get the following error:
_tls_common.js:130
c.context.loadPKCS12(pfx, passphrase);
^
Error: Unable to load BIO
at Error (native)
at Object.createSecureContext (_tls_common.js:130:17)
at Object.exports.connect (_tls_wrap.js:955:21)
at Agent.createConnection (https.js:73:22)
at Agent.createSocket (_http_agent.js:174:16)
at Agent.addRequest (_http_agent.js:143:23)
at new ClientRequest (_http_client.js:133:16)
at Object.exports.request (http.js:31:10)
at Object.exports.request (https.js:163:15)
at Request.start (/Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:747:30)
at Request.write (/Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:1369:10)
at end (/Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:561:16)
at Immediate._onImmediate (/Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:589:7)
at processImmediate [as _immediateCallback] (timers.js:374:17)
I have a sample app where the same code works.
I've tried to convert to .p12 without success.
Does anyone have an idea what this error might refer to?
Edit:
I'm using lodash to do a merge of 2 objects with dinamic properties and static properties
_.merge(options, _this.requestOptions);
And that was causing the problem
Looking at the nodejs source code (specifically this file https://github.com/nodejs/node/blob/master/src/node_crypto.cc)
the error is thrown by this function
// Takes .pfx or .p12 and password in string or buffer format
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
...
In line 964
in = LoadBIO(env, args[0]);
if (in == nullptr) {
return env->ThrowError("Unable to load BIO");
}
Where the LoadBIO returns null
// Takes a string or buffer and loads it into a BIO.
// Caller responsible for BIO_free_all-ing the returned object.
static BIO* LoadBIO(Environment* env, Local<Value> v) {
HandleScope scope(env->isolate());
if (v->IsString()) {
const node::Utf8Value s(env->isolate(), v);
return NodeBIO::NewFixed(*s, s.length());
}
if (Buffer::HasInstance(v)) {
return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
}
return nullptr;
}
Perhaps the buffer is somehow not readable? Also it seems that the function is expecting an utf-8 encoded string.
Some ideas:
Are you sure the path to the file is correct?
Maybe encoding issue? Did you try to set fs.readFileSync() encoding explicitly?
Try with fs.readFile(<filename>, <encoding>, function(error, data){}) to see if it throws an error?

Categories

Resources