twilio error 'username required' - javascript

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e";
var client = require('twilio')(process.env.AC55a59221acb23a5aa6f046740bb73317, process.env.TWILIO_TOKEN);
router.use(bodyParser.urlencoded({extended: true}));
router.use(bodyParser.json());
router.post('/', function(req, res) {
console.log('this is the req', req.body);
client.messages.creat({
to:'+19522209630',
from:'+17633249718',
body:'hello World'
}, function(err, data) {
if (err) {
console.log('err', err);
console.log('data', data);
}
});//en d of sendMessage
res.send(200);
});
module.exports = router;
/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/rest/Twilio.js:101
throw new Error('username is required');
^
Error: username is required
at new Twilio (/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/rest/Twilio.js:101:11)
at initializer (/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/index.js:8:10)
at Object.<anonymous> (/Users/moisesmiguelhernandez/Documents/prime/solo_project/routes/sendMessage.js:6:31)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/moisesmiguelhernandez/Documents/prime/solo_project/server.js:10:19)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! solo_project#1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the solo_project#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/moisesmiguelhernandez/.npm/_logs/2017-07-11T15_02_02_750Z-debug.log
I am getting and error that says username is required. I am trying to use twilio. I followed a youtube video and i have it like he does. Any suggestions on how to fix this? P.S The index file is the terminal error message

Save these into a .env file at your root of your folder
TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e"
TWILIO_ACCOUNT_SID = "AC55a59221acb23a5aa6f046740bb73317"
Then install
npm install dotenv --save
After that you can use these environment variables in your file like this:
require('dotenv');
var client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_TOKEN);```

I had this same issue as well. What fixed it for me is doing
npm install dotenv
require('dotenv').config()
then I added my
TWILIO_ACCOUNT_SID=***
TWILIO_AUTH_TOKEN=***
full code:
require('dotenv').config();
const accountSid = process.env.ACCOUNT_SID;
const authToken = process.env.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.calls
.create({
url: 'http://demo.twilio.com/docs/voice.xml',
to: process.env.CELL_PHONE,
from: process.env.TWIL_NUM,
})
.then(call => console.log(call.sid))
.catch(err => console.log(err));

var TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e";
var TWILIO_ACCOUNT_SID = "AC55a59221acb23a5aa6f046740bb73317";
var client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_TOKEN);
#philnash i changed it and fixed the creat typo but the terminal is still saying 'username is required'

Note -: This is not at all a good way but just a workaround. I will edit the answer as soon I will get the right way. This is just a trick which worked in my case.
const client = require('twilio')(<YOUR_ACCOUNT_SID>, <YOUR_ACCOUNT_KEY>);
basically use the keys directly instead of referencing through any variable.

Twilio developer evangelist here.
Aside from the typo in creat that Champa has pointed out in the comments, I think I know where you're going wrong. Your code currently has:
var client = require('twilio')(process.env.AC55a59221acb23a5aa6f046740bb73317, process.env.TWILIO_TOKEN);
I am guessing that it should have something like process.env.TWILIO_ACCOUNT_SID.
The account sid is effectively the username for accessing the API, which is why the error message says that.
Let me know if that helps at all.

I encountered this issue today and was getting message Error: username is required when running my twilio test. Since I am using dotenv, I have a .env file with my environment variables, and this is where I made a mistake. We have another app with the SID and TOKEN variables, so I copied them and left in the export keyword, i.e. export TWILIO_ACCOUNT_SID=..., but if using dotenv, the export keyword is not needed. I removed export and re-run my test script and it all worked, e.g.
TWILIO_ACCOUNT_SID=***
TWILIO_AUTH_TOKEN=***

I was working with a colleague when we encounter the same error. I tried almost all the solutions but didn't work for me (most of the solutions here are the same in a sense).
How we resolve this was amazing: how?
When you are using a file called .env for your environment variables, you need to double checks where you created this file
.env file must be created in your root directory. That means must be inside your project folder not inside sub-folder that is inside your project.
when you are to use it, make sure you reference the right variable. This mistake is
related to this question. such as
// index.js
// this wrong, notice process.env.AC55a59221acb23a5aa6f046740bb73317 in client variable
TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e";
var client = require('twilio')(process.env.AC55a59221acb23a5aa6f046740bb73317, process.env.TWILIO_TOKEN);
this is correct process.env.TWILIO_ACCOUNT_SID
// .env
TWILIO_ACCOUNT_SID=AC55a59221acb23a5aa6f046740bb73317
Twilio Documentation
Interested in the mistake we made, it's the wrong placement of .env file.

I have ran into this error earlier so, adding to the answers above make sure the .env file is in the root directory, all spellings are correct and dotenv package is used.

I figured out the issue that I was having with this. When starting up the server, make sure that you are in the directory that contains the .env file.

The Silly mistake which I made was, I used "SMS_SID: YourSID", It must be "SMS_SID = YourSID".

In my case, everything was correct except I was using the account_sid and auth_token of test credential instead of Live credential.

Related

Error when import of node module 'windows' in electrons

I am updating the node module of an application made by somebody else. The module used is 'windows' and the version that was used was 0.0.8. I updated electronjs to 22 and the node module 'windows' to the latest version 0.1.2.
I am using the module, as it was used before :
const windows = require('windows');
var a = windows.registry('/RegistryPath/').SomeValueName.value;
And I am getting the error :
A JavaScript error occurred in the main process
Uncaught Exception:
TypeError: Cannot read properties of undefined (reading 'split')
at Object.
(/path/node_modules/windows/lib/runnable.js:9:29) at
Module._compile (node:internal/modules/cjs/loader:1141:14) at
Module._extensions..js (node:internal/modules/cjs/loader:1196:10)
at Module.load (node:internal/modules/cjs/loader:1011:32) at
Module._load (node:internal/modules/cjs/loader:846:12) at f._load
(node:electron/js2c/asar_bundle:2:13328) at Module.require
(node:internal/modules/cjs/loader:1035:19) at require
(node:internal/modules/cjs/helpers:102:18) at Object.
(/path/node_modules/windows/index.js:4:17) at
Module._compile (node:internal/modules/cjs/loader:1141:14)
The error location is at runnable.js:9 :
var path = require('path');
var fs = require('fs');
var exists = require('./utility').exists;
var resolve = require('./utility').resolve;
var PATH = process.env.Path.split(';').filter(function(s){ return ~s.indexOf('node') });
I tried to read the environnemental variable in Linux and I found that if I modify the code of the module 'windows' to get process.env.PATH.split(';') instead of process.env.Path.split(';') I don't get the same error. The code move forward to the next conditional loop. But the filter of the line discussed here is looking for the string 'node'. In the case of an electron app when it is package there is no node_module folder. So I also hit the same next error when the app is package; which is :
//Bugfix taken from #schmittberger
if (!exists(PATH)) {
if (process.env.NODE_PATH) {
PATH = process.env.NODE_PATH
} else {
throw new Error('No bin-PATH found');
}
}
At this point I am receiving the Error('No bin-PATH found'). I don't have enough experience to know how to fix such an issue. Even if I add the path to my node bin in the environnemental variable of Linux I will hit the same error when the app is package for Windows as there are no folder "node_modules" in the packaged app.

TypeError: Cannot read property 'compile' of undefined

I'm currently trying to follow this tutorial for Ethereum Solidity coding, and for the following code:
const path = require('path');
const fs = require('fs'); // File system module
const solc = require('solc').default; // Solidity Compiler module
// Note that phrase resolving a link means to substitute the actual location in the file system for the symbolic link
// If we assume that logFile is a symbolic link to dir/logs/HomeLogFile, then resolving it yields dir/logs/HomeLogFile
// Generates a path that points directly to the inbox file. __dirname will be the root direction
// inboxPath = desktop/inbox/contracts/inbox.sol
const inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');
// The next step is to actually read the contents of the source file now
// utf8 is the encoding to read the file's content
const source = fs.readFileSync(inboxPath, 'utf8');
// Call solc.compile and pass in our source code, with only 1 contract
// console.log() means put the output in the console
console.log(solc.compile(source, 1));
I get the following error when I hover over const solc = require('solc').default:
Could not find a declaration file for module 'solc'. 'c:/Users/Hana PC/Desktop/inbox/node_modules/solc/index.js' implicitly has an 'any' type.
Try `npm i --save-dev #types/solc` if it exists or add a new declaration (.d.ts) file containing `declare module 'solc';`ts(7016)
When I try node compile.js, I get:
C:\Users\Hana PC\Desktop\inbox\compile.js:18
console.log(solc.compile(source, 1));
^
TypeError: Cannot read property 'compile' of undefined
at Object.<anonymous> (C:\Users\Hana PC\Desktop\inbox\compile.js:18:18)
[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)[39m
[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)[39m
[90m at Module.load (internal/modules/cjs/loader.js:928:32)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:769:14)[39m
[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)[39m
[90m at internal/main/run_main_module.js:17:47[39m
I've never used/interacted with TypeScript or JavaScript or anything of the sorts, so I honestly don't even know what this error means. I've already tried uninstalling and reinstalling solc multiple times, all to no avail.
My node.js version is:
6.14.8
I tried doing some searching online for what the implicitly has an 'any' type. means or how it could be fixed, but I honestly didn't get any of it. If it helps, my package.json looks like this:
{
"name": "inbox",
"version": "1.0.0",
"description": "",
"main": "compile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"solc": "^0.8.0"
}
}
Any help is appreciated!
**** Update:**
Tried it with uninstall solc and a fresh install (without using version 0.4.17), and got an Assertion Error:
assert.js:383
throw err;
^
AssertionError [ERR_ASSERTION]: Invalid callback object specified.
at runWithCallbacks (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:97:7)
at compileStandard (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:207:14)
at Object.compileStandardWrapper [as compile] (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:214:14)
Wish I knew what was goin on
As per the discussion we had above, since the solidity file is using v0.4.17, you should use the same version of solc library in your code.
I have created a working example of your code here and the only two changes required were:
Making sure I use v0.4.17 of solc.
Import const solc = require("solc"); and not const solc = require("solc").default;
If you are having trouble downgrading the solc package, then
Delete package-lock.json file and node_modules/ folder.
Update the package.json files dependency to "solc": "0.4.17" and not to "^0.4.17"
Simply run npm install one last time.
This should be enough to get you up and running.

Can't install discord.js / can't find module discord.js

I attempt to install Discord.JS by running npm install discord.js and it looks like it works, but it doesn't.
I get this error when running the index.js file, but it gives an error stating that discord.js is not found. So, I try to install it again:
PS G:\My Drive\coding\node.js\bot> npm install https://github.com/discordjs/discord.js.git
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN bot#0.0.1 No repository field.
+ discord.js#12.0.2
added 15 packages from 17 contributors and audited 15 packages in 97.377s
found 0 vulnerabilities
Then I run the index.js file:
const Discord = require('discord.js');
const bot = new Discord.Client();
const botCommands = require('./commands');
const { prefix, token } = require('./cfg.json');
bot.login(TOKEN);
bot.on('ready', () => {
console.info(`Logged in as ${bot.user.tag}!`);
});
This is the result displayed in console:
PS G:\My Drive\coding\node.js\bot> node .
internal/modules/cjs/loader.js:796
throw err;
^
Error: Cannot find module './commands'
Require stack:
- G:\My Drive\coding\node.js\bot\index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (G:\My Drive\coding\node.js\bot\index.js:3:21)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'G:\\My Drive\\coding\\node.js\\bot\\index.js' ]
}
Side note: Before I ran index.js, I ran npm init -y to create a package.
P.S: English is not my first language
If you cannot find the /commands folder - are you sure it is there? - make sure it is in the folder 'G:\My Drive\coding\node.js\bot\'.
Okay. First of all, it says the module "./commands" is not found, discord.js does exist.
The reason is, you are trying to import a folder. Node.js does not work that way.
You have to delete the line with the require("./commands") and replace it with something like this:
var botCommands = fs.readdirSync('./commands/');
That will return an array of file names in that directory.
Then, go on with whatever you were doing.
Make sure you are using the correct folder and you have commands folder in G:\My Drive\coding\node.js\bot
The error is in your 3rd line ou have require the commands
If you have commands folder do this
fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
I think what you want is something like
bot.on('message', message => {
if(message.content.startsWith(prefix)) {
let rawA = message.content.slice(prefix.length).split(' ');
let cmd = rawA[0];
let rawB = rawA.join(' ');
let args = rawB.slice(cmd.length).split(' ');
let cmdFile = require(`./commands/${cmd}.js`);
cmdFile.run(bot, message, args);
}
}
But if you use this, you need this in your command file:
exports.run = async (bot, message, args) => {
//code
}
Well, Ya see, If it says "commands is not found" then it could be that your folder might be wrong, double-check the capatalization and lowercases. And if still its showing wrong.
Make sure that your commands folder is actually in this directory.
G:\\My Drive\\coding\\node.js\\bot\\index.js
Hope this helped!

Why is bcrypt showing errors on TravisCI?

I am running tests on TravisCI but at the point, npm test is triggered, this error is thrown:
> store-manager#1.0.0 test /home/travis/build/danoseun/Store-Manager
> npm run createTables && nyc --reporter=html --reporter=text mocha ./server/tests/*.js --exit --compilers js:babel-core/register
> store-manager#1.0.0 createTables /home/travis/build/danoseun/Store-Manager
> babel-node -- ./server/db/dbTables
/home/travis/build/danoseun/Store-Manager/node_modules/bcrypt/bcrypt.js:92
throw new Error('data and salt arguments required');
^
**Error: data and salt arguments required**
at Object.hashSync (/home/travis/build/danoseun/Store-Manager/node_modules/bcrypt/bcrypt.js:92:15)
at Object.<anonymous> (/home/travis/build/danoseun/Store-Manager/server/db/dbTables/seedAdmin/insertAdmin.js:6:28)
at Module._compile (internal/modules/cjs/loader.js:721:30)
at loader (/home/travis/build/danoseun/Store-Manager/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/travis/build/danoseun/Store-Manager/node_modules/babel-register/lib/node.js:154:7)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Module.require (internal/modules/cjs/loader.js:657:17)
at require (internal/modules/cjs/helpers.js:22:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! store-manager#1.0.0 createTables: `babel-node -- ./server/db/dbTables`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the store-manager#1.0.0 createTables script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/travis/.npm/_logs/2019-01-15T14_24_23_739Z-debug.log
npm ERR! Test failed. See above for more details.
The command "npm test" exited with 1.
cache.2
store build cache
0.00s2.35snothing changed, not updating cache
Done. Your build exited with 1.
This is the way, the insertAdmin.js file looks like:
import bcrypt from 'bcrypt';
import pool from '../../connection';
const sql = 'insert into users (email, password, role) values ($1, $2, $3)';
const password = process.env.PASSWORD;
const newPassword = bcrypt.hashSync(password, 10);
const email = process.env.EMAIL;
const variables = [email, newPassword, 'admin'];
I also tried to restructure the file to use asynchronous hashing but it still didn't work.
const sql = 'insert into users (email, password, role) values ($1, $2, $3)';
const password = process.env.PASSWORD;
async function value() {
console.log('HERE', bcrypt.hash(password, 10))
const hashPassword = await bcrypt.hash(password, 10);
console.log('OYA', hashPassword);
return hashPassword;
}
const email = process.env.EMAIL;
const variables = [email, value(), 'admin'];
console.log('NOW', variables[1]);
console.log(bcrypt.hash(password, 10)) and console.log(hashPassword) return the correct values but console.log(variables[1]) returns an empty object.
I don't understand what could be wrong.
PS: I just did something. I unintentionally pushed the console.log(process.env.PASSWORD) in that file to github and integrated it with travis and behold, the line where I did console.log shows that process.env.PASSWORD is undefined. I have made further steps to import dotenv or dtenv/config but it's still undefined. What do I do?
process.env.PASSWORD is probably undefined since you forgot to configure environment variables on Travis CI. Since passwords are usually confidential, you should set the variable in the settings page of your repo, which will encrypt the password and keep it secret. See more info on how to do that here.
To add to the upvoted answer, data and salt arguments required error in bcrypt is thrown when one of the arguments to bcrypt.hashSync method is null according to https://github.com/kelektiv/node.bcrypt.js/blob/master/bcrypt.js line 92. To solve this on Travis, click on more options-settings and environmental variables on TravisCI of the repository and add(with the add button) the respective key as was specified in your .env file. Build should automatically restart and see it pass if other things are equal.

MongoDB - Error: Cannot find module '../build/Release/bson'

I tried to run a typescript example in the following way which caused following error:
$ mongod --dbpath /home/u/databases
$ npm install
$ tsc --sourcemap --module commonjs app.ts
$ node app.js
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
========================================================================================
= Please ensure that you set the default write concern for the database by setting =
= one of the options =
= =
= w: (value of > -1 or the string 'majority'), where < 1 means =
= no write acknowledgement =
= journal: true/false, wait for flush to journal before acknowledgement =
= fsync: true/false, wait for flush to file system before acknowledgement =
= =
= For backward compatibility safe is still supported and =
= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =
= the default value is false which means the driver receives does not =
= return the information of the success/error of the insert/update/remove =
= =
= ex: new Db(new Server('localhost', 27017), {safe:false}) =
= =
= http://www.mongodb.org/display/DOCS/getLastError+Command =
= =
= The default of no acknowledgement will change in the very near future =
= =
= This message will disappear when the default safe is set on the driver Db =
========================================================================================
/home/u/tmp/TypeScriptSamples/imageboard/app.js:9
app.configure(function () {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object.<anonymous> (/home/u/tmp/TypeScriptSamples/imageboard/app.js:9:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
Furthermore, looking at db.ts I think http and url are missing in package.json file, am I right?
How is it possible to fix the above error with mongodb?
in Linux operating system first remove bson folder from node_modules and run this command:
sudo apt-get install gcc make build-essential
and then restart nodejs file such as index.js. Hope its helpful
I am using connect-mongo for sessions. I had the same problem and was because the version of connect-mongo generated an error with the version 4.0.x of mongoose. You could check each version of the dependencies you are using.
looking at db.ts I think http and url are missing in package.json file, am I right?
No. These modules are a part of core nodejs.
The source of the error is the package.json specifying minimum numbers without backward in compatible version locks. https://github.com/Microsoft/TypeScriptSamples/blob/master/imageboard/package.json#L6 I would change '>=' to be harder versions e.g. 3.x

Categories

Resources