Nodemailer: Cannot find module 'net' + nodemailer.createTransport is not a function - vue.js

I am unable to understand why nodemailer is not working properly within a VUE.js app.
The code is from the nodemailer examples. Here is the method I call on form submit:
methods: {
submit() {
this.$refs.form.validate().then(() => {
"use strict";
const nodemailer = require("nodemailer");
async function main() {
let transporter = nodemailer.createTransport({
host:'mail.kakakakak',
port: 465,
secure: true,
auth: {
user: 'info#',
pass: '****'
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: "info#lopezi.com",
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>" // html body
});
console.log("Message sent: %s", info.messageId);
}
main().catch(console.error);
});
},
}
The first time I click the submit button I get the error:
Uncaught (in promise) Error: Cannot find module 'net'
at webpackEmptyContext (eval at ./node_modules/defaultable sync recursive (app.5176eebb0babf67e88fb.hot-update.js:22), <anonymous>:2:10)
at Object.workaround_require (defaultable.js?6987:49)
at require (defaultable.js?6987:77)
at eval (server.js?663d:9)
at defaulter (defaultable.js?6987:83)
at defaultable (defaultable.js?6987:63)
at good (defaultable.js?6987:174)
at Object.eval (server.js?663d:5)
at eval (server.js:242)
at Object../node_modules/hbo-dnsd/server.js (chunk-vendors.5176eebb0babf67e88fb.hot-update.js:2053)
The second time I click the submit button, still with the same content in there I get the error:
TypeError: nodemailer.createTransport is not a function
at _callee$ (ContactForm.vue?2be1:64)
at tryCatch (runtime.js?96cf:45)
at Generator.invoke [as _invoke] (runtime.js?96cf:271)
at Generator.prototype.<computed> [as next] (runtime.js?96cf:97)
at asyncGeneratorStep (asyncToGenerator.js?3b8d:5)
at _next (asyncToGenerator.js?3b8d:27)
at eval (asyncToGenerator.js?3b8d:34)
at new Promise (<anonymous>)
at new F (_export.js?63b6:36)
at eval (asyncToGenerator.js?3b8d:23)

Related

NuxtJs - Cannot sign JWT

I have a NuxtJS (v2.15.8) app that needs to consume an API on GCP App Engine (NodeJS) protected by IAP. I'm trying to get an access token for the Service Account I've created as described here: https://cloud.google.com/iap/docs/authentication-howto
I've searched a lot but I can't find on Google nobody with the same or similar need.
After several attempts with different methods, now I'm trying to sign a JWT in my code in order to get the access token from the API.
To do this I'm using functions from cryptojs lybrary to create the signature, but I have a problem with the sign() function. It gives me this error:
TypeError: Cannot read properties of null (reading '2')
at module.exports (fixProc.js?4dd0:14:1)
at parseKeys (index.js?2aee:19:1)
at sign (sign.js?6fe7:11:1)
at Sign.signMethod [as sign] (index.js?b692:42:1)
at _callee2$ (auth.js?889e:78:1)
at tryCatch (runtime.js?96cf:63:1)
at Generator.invoke [as _invoke] (runtime.js?96cf:294:1)
at Generator.eval [as next] (runtime.js?96cf:119:1)
at asyncGeneratorStep (asyncToGenerator.js?1da1:3:1)
at _next (asyncToGenerator.js?1da1:25:1)
Here's the code I'm using
const qs = require('qs');
const crypto = require('crypto');
const private_key_id=options.private_key_id
const client_email=options.client_email
const private_key=options.private_key
const issued_at=Math.round(+new Date()/1000);
const expires_at=issued_at+3600
const header="{'alg':'RS256','typ':'JWT','kid':'"+private_key_id+"'}"
const header_base64=Buffer.from(header).toString('base64')
const body="{'iss':'"+client_email+"','aud':'"+oauth_token_uri+"','exp':"+expires_at+",'iat':"+issued_at+",'sub':"+client_email+",'target_audience':'"+iap_client_id+"'}"
const body_base64=Buffer.from(body).toString('base64')
const sign = crypto.createSign('sha256');
sign.write(Buffer.from(`${header_base64}.${body_base64}`));
sign.end();
const signature_base64=sign.sign(private_key,'base64');
const assertion=Buffer.from(`${header_base64}.${body_base64}.${signature_base64}`)
axios({
method: 'post',
url: 'https://www.googleapis.com/oauth2/v4/token',
data: qs.stringify({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: assertion
}),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
All the variables used are taken from the service account credentials JSON file and set as env variables in my app.
I solved using
const sign = crypto.createSign('RSA-SHA256');
instead of
const sign = crypto.createSign('sha256');

Short stack trace with async await in protractor 7

I'm trying to automate some tests with protractor and jasmine and I'm using async/await to resolve the promises.
The issue is, when an error does happen, the stack trace is TOO short and thus, I can't seem to locate the source of the issue.
I did make sure to put SELENIUM_PROMISE_MANAGER to FALSE in the config file.
I'm using protractor 7 along with node 14.16.0
Does anyone know how to solve this ? There are not enough details
Here's a code snippet
const invoicesButton: Button = new Button("Invoices", LocatorType.Href, "#/Invoices");
describe("Kouka test", function () {
beforeEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000000;
});
it("Does a random test", async function () {
await browser.get("https://appdev.expensya.com/Portal/#/Login?lang=en");
await loginEmailInput.typeText("amr.refacto#yopmail.com")
await loginPasswordInput.typeText("a")
await loginButton.click(true);
await dashboardPage.invoicesButton.click().catch((e) => {
e.stackTraceLimit = Infinity;
throw e;
});
await userInvoicesPage.createManualInvoice(invoice).catch((e) => {
e.stackTraceLimit = Infinity;
console.error("TEST ERROR ", e);
throw e;
});
await browser.sleep(10000);
});
});
And here's the definition of the "Button" Class:
import { browser } from "protractor";
import { WebComponent } from "./webComponent";
export class Button extends WebComponent {
/**
* #param webElementText Text that the web element contains.
* #param locatorType Locator type of the web element to search for.
* #param locator Locator of the web element to search for.
* #param parentElement Parent Web Component if it exists.
*/
constructor(webElementText, locatorType, locator, parentElement: WebComponent = null) {
super(webElementText, locatorType, locator, parentElement);
}
async click(usingJavaScript = false) {
if (usingJavaScript) {
await this.isPresent();
await browser.executeScript("arguments[0].click();", await this.webElement)
}
else {
await this.isVisible();
await this.isClickable();
await this.webElement.click();
}
}
}
Finally, here's the stack trace
Started
Jasmine started
undefined
F
Kouka test
× Does a random test
- Failed: Wait timed out after 10012ms
at C:\Users\Amrou Bellalouna\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2201:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:20:5)
at Object.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:15:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
Failures:
1) Kouka test Does a random test
Message:
Failed: Wait timed out after 10012ms
Stack:
TimeoutError: Wait timed out after 10012ms
at C:\Users\Amrou Bellalouna\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2201:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:20:5)
at Object.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:15:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
1 spec, 1 failure
Finished in 19.461 seconds
I remember trying to solve this a while ago and I couldn't. But I implemented a bunch of workarounds and apparently this was enough
To begin, can you share what these are doing
await this.isPresent();
await this.isVisible();
await this.isClickable();
Having this function
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime
)
}
you can use an advantage of third argument of browser.wait as described here and include an optional message on failure like this
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime,
`Element ${this.webElement.locator().toString()} is not present after ${this._elapsedTime}ms`);
)
}
(I'm giving you all my secret sauce ingredients haha) If you add this to onPrepare in the config
/**
* Set global environment configuration
*/
Object.defineProperty(global, '__stack', {
get: function() {
let orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) {
return stack;
};
let err = new Error();
Error.captureStackTrace(err, arguments.callee);
let stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
},
});
// returns name of the file from which is called
Object.defineProperty(global, '__file', {
get: function() {
let path = __stack[1].getFileName();
try {
//*nix OSes
return path.match(/[^\/]+\/[^\/]+$/)[0];
} catch (error) {
//Windows based OSes
return path.match(/[^\\]+\\[^\\]+$/)[0];
}
},
});
// returns function name from which is called
Object.defineProperty(global, '__function', {
get: function() {
return __stack[1].getFunctionName();
},
});
// returns line number of the position in code when called
Object.defineProperty(global, '__line', {
get: function() {
return __stack[1].getLineNumber();
},
});
then you can use it for logging the file name, function name, and the line where it's called
For example,
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime,
`Failed at ${__file} -> ${__function}() -> line ${__line}`
)
}
will result in this error
- Failed: Failed at common/index.js -> isVisible() -> line 82
Wait timed out after 1032ms
Wait timed out after 1032ms
So you can accommodate this to your needs
also I just realized you may want to play around with __stack variable itself

Vue.js Vuex action do not see getter from other module

Im trying to use getter from other module to get JWT token to my http query, which is looking like that:
...
},
actions: {
async refreshContactData( state, getters, rootState, rootGetters ) {
return axios.get('/test', {
headers: {
Authorization: 'Bearer ' + rootGetters['user/getJWT']//the token is a variable which holds the token
}
}).then(response => {
console.log(response)
})
}
},
}
my second modlue look like this:
//user.js
import axios from "axios"
export default {
state: {
jwt: 'asdfasdf',
},
getters: {
getJWT: (state) => {
console.log("WTF")
return state.jwt;
}
},
...
its connected with main index.js store file:
//index.js
...
modules: {
user: User,
contact: Contact
},
...
i tried different configuration but im still getting "undefined" error in console:
vue.runtime.esm.js?2b0e:1888 TypeError: Cannot read property 'user/getJWT' of undefined
at _callee$ (contact.js?7526:54)
at tryCatch (runtime.js?96cf:63)
at Generator.invoke [as _invoke] (runtime.js?96cf:293)
at Generator.eval [as next] (runtime.js?96cf:118)
at asyncGeneratorStep (asyncToGenerator.js?1da1:3)
at _next (asyncToGenerator.js?1da1:25)
at eval (asyncToGenerator.js?1da1:32)
at new Promise (<anonymous>)
at eval (asyncToGenerator.js?1da1:21)
at Store.refreshContactData (contact.js?7526:47)
What am i doing wrong?
Actions don't have multiple arguments like getters do. They have a context argument and a payload argument. To get the rootGetters you can destructure the context argument:
async refreshContactData({ rootGetters }) { // notice the braces
...
}
Then rootGetters will be defined.

Why is HERE Places API not working on device but on localhost?

I am trying to implement a location search API from HERE places-api inside an Ionic5 app.
Everything works fine in localhost environment but search stops working on the device.
Question: Is there a special App-Code or -Key for the use of devices (also for testing via Android Studio)? And why is it working on localhost and not on the device by testing with android-studio?
I tried to change app-code & app-id into app-key and tried also Rest, JS and Rest-JS auth credentials but it is not working. I have no idea what to do next because there is no error at testing on the device, there is just no reaction to this API.
index.html
<script
src="https://js.api.here.com/v3/3.0/mapsjs-core.js"
type="text/javascript"
charset="utf-8"
></script>
<script
src="https://js.api.here.com/v3/3.0/mapsjs-service.js"
type="text/javascript"
charset="utf-8"
></script>
<script
src="https://js.api.here.com/v3/3.0/mapsjs-places.js"
type="text/javascript"
charset="UTF-8"
></script>
Search service
public async searchLocation(search): Promise<any> {
var platform = new H.service.Platform({
app_id: "my-id",
app_code: "my-code",
});
var searchParams = {
q: search,
in: "-180,-90,180,90"
};
return this.startSearch(platform, searchParams);
}
public async startSearch(platform: any, searchParams: object): Promise<any> {
return new Promise((resolve, reject) => {
var search = new H.places.Search(platform.getPlacesService());
const self = this;
search.request(
searchParams,
{},
function onResult(data: any) {
self.Result = data.results.items;
resolve(self.Result);
},
function onError(error: any) {
console.log("HERE search error", error);
reject(error);
}
);
});
}
EDIT - Error log
E/Capacitor/Console: File: http://localhost/vendor-es2015.js - Line 43427 - Msg: ERROR Error: Uncaught (in promise): Error: [timeout] http://places.api.here.com/places/v1/discover/explore?xnlp=CL_JSMv3.0.17.0&app_id=--myID--&app_code=--myCode--&in=49.9949556%2C10.1767104%3Br%3D10000&size=100 request failed
Error: [timeout] http://places.api.here.com/places/v1/discover/explore?xnlp=CL_JSMv3.0.17.0&app_id=--myID--&app_code=--myCode--&in=479.9949556%2C10.1767104%3Br%3D10000&size=100 request failed
at Object.Zc (eval at <anonymous> (https://js.api.here.com/v3/3.0/mapsjs-core.js:56:36), <anonymous>:11:176)
at b (eval at <anonymous> (https://js.api.here.com/v3/3.0/mapsjs-core.js:56:36), <anonymous>:9:440)
at eval (eval at <anonymous> (https://js.api.here.com/v3/3.0/mapsjs-core.js:56:36), <anonymous>:10:43)
at ZoneDelegate.invokeTask (http://localhost/polyfills-es2015.js:3741:31)
at Object.onInvokeTask (http://localhost/vendor-es2015.js:73280:33)
at ZoneDelegate.invokeTask (http://localhost/polyfills-es2015.js:3740:60)
at Zone.runTask (http://localhost/polyfills-es2015.js:3518:47)
at invokeTask (http://localhost/polyfills-es2015.js:3815:34)
at ZoneTask.invoke (http://localhost/polyfills-es2015.js:3804:48)
FIXED:
Thanks #Raymond, i fixed the usecase with another way.
Instead of my API call of my question i changed it to URL request by httpClient.
public async searchLocation(search): Promise<any> {
const BASE_NOMINATIM_URL = "nominatim.openstreetmap.org";
const DEFAULT_VIEW_BOX = "-25.0000%2C70.0000%2C50.0000%2C40.0000";
const url = `https://${BASE_NOMINATIM_URL}/search?format=json&q=${search}&${DEFAULT_VIEW_BOX}&bounded=1`;
return this.http.get(url).subscribe((ans) => {
console.log("data", ans);
});
}
I don't know why the way inside my question is not working. But the URL way works.

Solidity TypeError: artifacts is not a function

I am a student learning to write smart contracts using solidity. When running these codes using truffle(ganache):
Helloworld.sol
pragma solidity 0.5.12;
contract Helloworld {
string message = "Hello World";
function getMessage() public view returns (string memory) {
return message;
}
function setMessage(string memory newMessage) public payable {
message = newMessage;
}
}
Helloworld_migration.js
const Helloworld = artifacts.require("Helloworld");
module.exports = function(deployer, network, accounts){
deployer.deploy(Helloworld).then(function(instance){
instance.setMessage("Hello Again!", {value: 1000000, from: accounts[0]}).then(function(){
console.log("Success");
}).catch(function(err){
console.log("error: " + err);
});
}).catch(function(err){
console.log("Deploy failed " + err);
});
};
Helloworldtest.js
const Helloworld = artifacts().require("Helloworld");
contract("Helloworld", async function(){
it("should initialize correctly", async function(){
let instance = await Helloworld.deployed();
let message = await instance.getMessage();
assert(message === "Hello Again!");
});
});
I received this error msg:
TypeError: artifacts is not a function
at Object.<anonymous> (/Users/cherrybluemoon/projects/test/Helloworldtest.js:1:20)
at Module._compile (internal/modules/cjs/loader.js:1123:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
at Module.load (internal/modules/cjs/loader.js:972:32)
at Function.Module._load (internal/modules/cjs/loader.js:872:14)
at Module.require (internal/modules/cjs/loader.js:1012:19)
at require (internal/modules/cjs/helpers.js:72:18)
at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:231:27
at Array.forEach (<anonymous>)
at Mocha.loadFiles
(/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:228:14)
at Mocha.run
(/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:536:10)
at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-
core/lib/test.js:135:1
at processTicksAndRejections (internal/process/task_queues.js:97:5)
You have to remove "()" from artifacts.
const Helloworld = artifacts.require("Helloworld");
Helloworld_migration.js is an invalid file name for a migration file. It needs to start with a number such as 1_migration.js or 1_helloworld_migration.js