Why is bcrypt showing errors on TravisCI? - javascript

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.

Related

TypeError: Cannot read property 'length' of undefined - While deploying using hardhat

I am getting the following error while trying to deploy a Mock contract on the hardhat development chain.
I am following:
Learn Blockchain, Solidity, and Full Stack Web3 Development with JavaScript – 32-Hour Course by Patrick Collins on FreeCodeCamp YT channel
I got this error while I was at 10:48:53 of the above course. I tried almost every thing but nothing helped but I found where the problem was occurring.
Ques: Where do I think the problem is occurring? (12:26)
According to me the problem is at the line where we are trying to deploy the script and we are waiting for the promise to be returned.
Here is the error:
Error: ERROR processing /Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/deploy/00-deploy-mocks.js:
TypeError: Cannot read property 'length' of undefined
at getFrom (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/helpers.ts:1713:14)
at _deploy (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/helpers.ts:533:9)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at _deployOne (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/helpers.ts:1004:16)
at Object.module.exports [as func] (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/deploy/00-deploy-mocks.js:12:26)
at DeploymentsManager.executeDeployScripts (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1219:22)
at DeploymentsManager.runDeploy (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1052:5)
at SimpleTaskDefinition.action (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/index.ts:438:5)
at Environment._runTaskDefinition (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
at Environment.run (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
at DeploymentsManager.executeDeployScripts (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1222:19)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at DeploymentsManager.runDeploy (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1052:5)
at SimpleTaskDefinition.action (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/index.ts:438:5)
at Environment._runTaskDefinition (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
at Environment.run (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
at SimpleTaskDefinition.action (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/index.ts:584:32)
at Environment._runTaskDefinition (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat/src/internal/core/runtime-environment.ts:219:14)
at Environment.run (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat/src/internal/core/runtime-environment.ts:131:14)
at SimpleTaskDefinition.action (/Users/rishavsharma/Documents/working/Web Dev/Blockchain/Freecodecamp/solidity&Block/blockchain-with-js/buyMeACoffee-dapp/node_modules/hardhat-deploy/src/index.ts:669:5)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
rishavsharma#Rishavs-Air buyMeACoffee-dapp %
Here is the code snippet in which I am getting the error:
const { network } = require("hardhat");
const { developmentChains, DECIMALS, INITIAL_ANSWER } = require("../helper-hardhat-config");
module.exports = async ({ getNamedAccounts, deployments }) => {
const { deploy, log } = deployments;
const { deployer } = await getNamedAccounts();
const chainId = network.config.chainId;
if (chainId == 31337) {
console.log("Development network detected! Deploying mocks...");
const feedMock = await deploy("MockV3Aggregator", {
contract: "MockV3Aggregator",
from: deployer,
log: true,
args: [DECIMALS, INITIAL_ANSWER],
});
log("Price Feed Mock deployed!");
log("==============================================");
}
}
module.exports.tags = ["all", "mocks"];
Please help me with this problem 🥹
I posted this question on Ethereum Stack Exchange but got no help.
System configuration: MacBook Air M1 2021 - Monterey 12.4, yarn: 1.22.18, Hardhat: 2.9.6
I got the answer from the MASTER himself, #PatrickAlphaC.
When we call await getNamedAccounts in the above code, hardhat looks for the length of the named accounts in our hardhat.config.js
We have to make sure that the property given below is in there!
namedAccounts: {
deployer: {
default: 0, // here this will by default take the first account as deployer
},
},
This solved my problem and I was HAPPY again!
Make sure you have await in getNamedAccount(). Also name must be correct.
Must have correct entry for named accounts as below:
namedAccounts: {
deployer: {
default: 0,
deployer
1: 0,
},
},
I was stuck for a while with this as well, and was also following this same course.
Cannot read properties of undefined (reading 'length')
at getFrom (/Users/ilima/hh-fcc/hardhat-fundme-fcc/node_modules/hardhat-deploy/src/helpers.ts:1713:14)
at _deploy (/Users/ilima/hh-fcc/hardhat-fundme-fcc/node_modules/hardhat-deploy/src/helpers.ts:533:9)
Initially I was writing from scratch and kept getting this error and plus hardhat npm installation. I decided to test just in case the course code, so I cloned the repo and surprisingly was also struggling with npm install issues for hardhat and waffle.
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: hardhat-project#undefined
npm ERR! Found: #nomiclabs/hardhat-ethers#0.3.0-beta.13
npm ERR! node_modules/#nomiclabs/hardhat-ethers
npm ERR! dev #nomiclabs/hardhat-ethers#"npm:hardhat-deploy- ethers#^0.3.0-beta.13" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer #nomiclabs/hardhat-ethers#"^2.0.0" from #nomiclabs/hardhat-waffle#2.0.2
npm ERR! node_modules/#nomiclabs/hardhat-waffle
npm ERR! dev #nomiclabs/hardhat-waffle#"^2.0.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
So fixing dependency hardhat-ethers by overriding it, fixed all issues for me, so try this:
"devDependencies": {
...
"#nomiclabs/hardhat-ethers": "npm:hardhat-deploy-ethers#^0.3.0-beta.13",
...
},
"overrides": {
"#nomiclabs/hardhat-waffle": {
"#nomiclabs/hardhat-ethers": "$#nomiclabs/hardhat-ethers"
}
}
I got solution from Installation advice breaks #nomiclabs/hardhat-waffle
Now, I noticed that you have already solved your problem, but I wanted to add my solution as well just in case if someone else is struggling with deploy being undefined in terminal. In my case namedAccounts and await getNamedAccount() was fine.

Inserting uuid into sqlite Database in node doesnt work

I am currently working on inserting a uuid-value like this one:
c1f9ff70-71e8-11eb-8b1b-77c34b246f91
into a sqlite database. This is my insert-Statement:
this.db.serialize(() => {
this.db.prepare(`CREATE TABLE IF NOT EXISTS bestellung(bid BLOB PRIMARY KEY, drink TEXT,price REAL,validation TEXT)`).run().finalize();
});
//FUNKTIONIERT!
const bidJSON = getBID();
const name = 'Testdrink';
const preis = 12.90;
const kpreis = preis.toFixed(2);
preis.toFixed(2);
console.log(bidJSON.id);
console.log(name);
console.log(kpreis);
var statement = "INSERT INTO bestellung(bid, drink, price, validation) VALUES(`" + bidJSON.id + "`,`" + name + "`,`" + kpreis + "`, `pending`)";
this.db.prepare(statement);
This is the error I get:
[Error: SQLITE_ERROR: no such column: c1f9ff70-71e8-11eb-8b1b-77c34b246f91
Emitted 'error' event on Statement instance at:
] {
errno: 1,
code: 'SQLITE_ERROR'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! bk#0.0.0 start: `node app`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bk#0.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! C:\Users\prakt\AppData\Roaming\npm-cache\_logs\2021-02-18T12_56_46_751Z-debug.log
I hope someone can help me!
For experienced programmers it should be an easy task.
I think it will probably be a mistake in my statement. I already read, that you can save the uuid into a blob and that this is the fastest way of saving it...
so i would like to stick to that.
Thank you in advance!

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 can't I deploy this code to firebase functions? I don't understand the error

I'm new to firebase functions - obviously - and I'm trying to test to see if an email in that specific path of the database when created is being used by an account if it isn't being used then change that database value accordingly. Here's the code:
exports.checkEmail = functions.database.ref('/checkEmailExistance')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const email = snapshot.val();
console.log('Email:', email, context.params.pushId);
admin.auth().getUserByEmail(email)
.then(snapshot => {
const data = snapshot.toJSON()
return admin.database().ref('checkEmailExistance').child(email).set("Nope")
})
});
and the error is:
ERROR: /Users/nathan/Documents/FirebaseFunctionsClipify/functions/src/index.ts:41:7 - Promises must be handled appropriately
ERROR: /Users/nathan/Documents/FirebaseFunctionsClipify/functions/src/index.ts:42:13 - Shadowed name: 'snapshot'
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions# lint: `tslint --project tsconfig.json`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the functions# lint 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/nathan/.npm/_logs/2019-04-25T16_21_29_696Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code2
UPDATE:
I changed the code so the errors shouldn't be produced again, but still got the same error:
exports.checkEmail = functions.database.ref('/checkEmailExistance')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const email = snapshot.val();
console.log('Email:', email, context.params.pushId);
return admin.auth().getUserByEmail(email)
.then(snap => {
const data = snap.toJSON()
return admin.database().ref('checkEmailExistance').child(email).set("Nope")
})
});
The second error is telling you that you redefined an existing variable called snapshot. Note that snapshot is defined by at the top level of your function callback, then again in the then callback. The second instance is "shadowing" the first, which is a potential error in your code. Just name the second variable something different.
The first lint error is telling you that you have an unhandled promise in your code. You can fix this by returning the promise from admin.auth().getUserByEmail().then(...):
return admin.auth().getUserByEmail(email)
.then(snap => {
const data = snap.toJSON()
return admin.database().ref('checkEmailExistance').child(email).set("Nope")
})

twilio error 'username required'

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.

Categories

Resources