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?
Related
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.
I'm building a React web app, where I want to use the query from a URL to search a MongoDB Database, and find an entry by its ID.
I have the following example URL:
www.examplewebsite.com/:id
In practice, the example URL would look like this in the browser:
www.examplewebsite.com/5f8da21ba227e300076c3299
Using JavaScript, how would I access the id (5f8da21ba227e300076c3299) from that URL?
I figured I may be able to do something like this...
const queryString = window.location.search;
console.log(queryString)
// 5f8da21ba227e300076c3299
However, since the ID is not preceded by a query question mark, I'm guessing that wouldn't work...
I could use a hacky approach of adding a '?' after the URL perhaps in my Router (this is for a React web app), however not sure that would be consistently the best approach.
Does anyone have any tips?
EDIT: I've added the suggestions below into my serverless function, and tried to log the result. Here's my code:
module.exports = async (req, res) => {
let urlOne = window.location.pathname.split('/').pop();
let urlTwo = window.location.pathname.split('/');
console.log(urlOne);
console.log(urlTwo);
};
It's returning the following error however when I call the function:
2020-10-23T10:23:37.878Z 91f31b36-0986-44a1-a7d1-fbd31e066ea6 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"ReferenceError: window is not defined","reason":{"errorType":"ReferenceError","errorMessage":"window is not defined","stack":["ReferenceError: window is not defined"," at module.exports (/var/task/api/fetchEditDebt.js:12:16)"," at Server.<anonymous> (/var/task/___now_helpers.js:813:19)"," at Server.emit (events.js:315:20)"," at parserOnIncoming (_http_server.js:790:12)"," at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: ReferenceError: window is not defined"," at process.<anonymous> (/var/runtime/index.js:35:15)"," at process.emit (events.js:327:22)"," at processPromiseRejections (internal/process/promises.js:209:33)"," at processTicksAndRejections (internal/process/task_queues.js:98:32)"]}
Unknown application error occurred
You can use:
window.location.pathname.split('/')
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'
I'm using a library called python-shell to try and send data back and forth between node and python.
The code below should work but when I run it I get this error:
events.js:160
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at exports._errnoException (util.js:1022:11)
at Socket._writeGeneric (net.js:712:26)
at Socket._write (net.js:731:8)
at doWrite (_stream_writable.js:334:12)
at writeOrBuffer (_stream_writable.js:320:5)
at Socket.Writable.write (_stream_writable.js:247:11)
at Socket.write (net.js:658:40)
at PythonShell.send (C:\Users\user\Desktop\node py project\fourth draft\node
_modules\python-shell\index.js:205:16)
at Object.<anonymous> (C:\Users\user\Desktop\node py project\fourth draft\in
dex.js:4:9)
at Module._compile (module.js:570:32)
my index.js:
var PythonShell = require('python-shell');
var pyshell = new PythonShell('script.py');
pyshell.send(JSON.stringify([1,2,3,4,5]));//the problem function
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
});
my script.py:
import sys, json
#Read data from stdin
def read_in():
lines = sys.stdin.readlines()
# Since our input would only be having one line, parse our JSON data from that
return json.loads(lines[0])
def main():
#get our data as an array from read_in()
lines = read_in()
# Sum of all the items in the providen array
total_sum_inArray = 0
for item in lines:
total_sum_inArray += item
#return the sum to the output stream
print total_sum_inArray
# Start process
if __name__ == '__main__':
main()
I think it has to do with the env path for python on win 7.
Any ideas? Library docs are located here: https://github.com/extrabacon/python-shell. Also I'm on Windows 7 Node v6.9.2 Python v3.6.1.
Try passing the parameter of python path to the script as below
var pyshell = new PythonShell('script.py',{pythonPath : '<path/to/python>'});
In this way you are explicitly setting the path to python executable command, regardless of any OS.
Here is reference of all the available options, that can be passed to the python-shell constructor.
Hope this fixes the issue, if it has to do anything with the Python path issues.
Server :
Meteor.publish('trades', function() {
return Trades.find();
});
Client:
Meteor.subscribe("trades");
Both:
Trades = new Meteor.Collection('trades');
When I run meteor, its giving me
TypeError: Object # has no method 'subscribe'
Any suggestions?
You might have your client code running in the root directory /. It would also then execute on the server and give this error. (Not sure if its this).