I want to implement SMS verification on a Node.js Server that when I am sending request to a URL with user phone number I could send verification SMS to that phone number, I read the documentation here and still, there is an error when I want to import sinch to my app
like codes below
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 5000;
const path = require('path');
const fetch = require('node-fetch');
var APPLICATION_KEY = 'MYAPP_KEY' ;
var SinchClient = require('sinch-rtc');
var sinchClient = new SinchClient({
applicationKey: APPLICATION_KEY,
capabilities: {messaging: true},
onLogMessage: function(message) {
console.log(message);
}
});
sinchClient.start(CREDENTIALS).then(function() {
console.log('Success!');
})
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('pages/index'))
.get('/test', (req, res) => {
//mycodes to verify phone number
})
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
it will give me this error
(function (exports, require, module, __filename, __dirname)
{ function Notification(e,t,i,n){this.progress=e/t,this.message=i,this.object=n}function getBrowserInfo(){var e,t=navigator.userAgent,i=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||t.match(/(applewebkit(?=\/))\/?\s*(\d+)/i)||[];return/trident/i.test(i[1])?"IE "+((e=/\brv[ :]+(\d+)/g.exec(t)||[])[1]||""):"Chrome"===i[1]&&null!=(e=t.match(/\bOPR\/(\d+)/))?"Opera "+e[1]:(i=i[2]?[i[1],i[2]]:[navigator.appName,navigator.appVersion,"-?"],null!=(e=t.match(/version\/(\d+)/i))&&i.splice(1,1,e[1]),i.join("/").substring(0,50))}function getPlatformInfo(){return navigator.platform}
function Sinch(e){if(!e)throw new TypeError("Could not create SinchClient, configuration not provided.");if(e.capabilities=e.capabilities||{},"string"!=typeof e.applicationKey)throw new TypeError("Could not create SinchClient, applicationKey is not a string");this.c
TypeError: Cannot read property 'indexOf' of undefined
at new Sinch (C:\Users\user\project\node_modules\sinch-rtc\lib\sinch.node.min.js:1:1741)
at Object.<anonymous> (C:\Users\user\project\server.js:9:13)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
Thanks in Advance
To send sms you should not set messaging to to true, in fact i would use this for node
https://www.npmjs.com/package/sinch-verification
Related
while running my first MEAN stack application i am getting this error:
\contactlist\node_modules\express\lib\router\index.js:502
this.stack.push(layer);
^
TypeError: Cannot read property 'push' of undefined
at Function.route (C:\Users\Mahima Kaushik\Desktop\contactlist\node_modules\express\lib\router\index.js:502:14)
at Function.proto. [as post] (C:\Users\Mahima Kaushik\Desktop\contactlist\node_modules\express\lib\router\index.js:509:22)
at Object. (C:\Users\Mahima Kaushik\Desktop\contactlist\routes\route.js:11:8)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Module.require (internal/modules/cjs/loader.js:1140:19)
at require (internal/modules/cjs/helpers.js:75:18)
at Object. (C:\Users\Mahima Kaushik\Desktop\contactlist\app.js:9:15)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
contactlist/app.js
var express = require('express');
var mongoos = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//connect to mongodb
mongoos.Mongoose.connect('mongodb://localhost:27017/contactlist');
//on connection
Mongoose.connection.on('connected',()=>{
console.log('connected to database mongodb #2717');
});
Mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('error in database connection:'+err);
}
});
//port number
const port = 3000
//adding middleware -cors
app.use(cors());
//boday-parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname,'public')));
//add routes
app.use('/api',route);
//testing
app.get('/',(req,res)=>{
res.send('contactlist');
});
app.listen(port,()=>{
console.log('server started at port:'+port);
});
contactlist/routes/route.js
const { Router } = require('express');
const express = require("express");
const router = express.Router();
//retrieving contacts
router.get('/contacts',(req,res,next) =>{
res.send('retrieving the contact list');
});
//add contacts
Router.post('/contact',(req , res, next)=>{
//logic
});
//delete contacts
Router.delete('/contact/:id',(req , res, next)=>{
//logic
});
module.exports = router;
You didn't create route correctly. The .get, .post and .delete are instance methods of Router instance, NOT static method. For more info, see Routing
routes/route.js should be:
const { Router } = require('express');
const router = Router();
//retrieving contacts
router.get('/contacts', (req, res, next) => {
res.send('retrieving the contact list');
});
//add contacts
router.post('/contact', (req, res, next) => {
//logic
});
//delete contacts
router.delete('/contact/:id', (req, res, next) => {
//logic
});
module.exports = router;
When setting up my router file.
I get
TypeError: Cannot read property 'apply' of undefined at /Users/evibreukers/Desktop/NODEJS/beginnerguide/node_modules/express/lib/router/index.js:635:15
at next (/Users/evibreukers/Desktop/NODEJS/beginnerguide/node_modules/express/lib/router/index.js:210:14)
at Function.handle (/Users/evibreukers/Desktop/NODEJS/beginnerguide/node_modules/express/lib/router/index.js:174:3)
at router (/Users/evibreukers/Desktop/NODEJS/beginnerguide/node_modules/express/lib/router/index.js:47:12)
at Object. (/Users/evibreukers/Desktop/NODEJS/beginnerguide/server.js:20:20)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
The problem is within the express library.
I am not sure where the problem is within my code because I did not use the apply method myself.
/router/index.js
const express = require('express');
const router = express.Router();
router.get('/',function(req,res){
res.render('index.html')
});
router.get('/about',function(req,res){
res.render('about.html');
});
router.get('/all', function (req, res) {
res.send(projectData);
// console.log(req);
});
module.exports.data = data = []
router.post('/addName', function (req, res) {
data.push(req.body);
console.log(data);
});
module.exports = router;
server.js
projectData = {};
// --> npm init (set up package.json)
// --> npm install express
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/static'));
// --> npm install cors
const cors = require('cors');
app.use(cors());
// --> npm install ejs
require('./routes')(app);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// --> npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// connect with routes file
app.use(require('./routes'));
// set up PORT
const port = 3000;
const server = app.listen(port,function(){
console.log(`We have started our server on port ${port}`);
});
/static/app.js
const postData = async ( url = '', data = {})=>{
console.log(data);
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {'Content-Type': 'application/json',},
// Body data type must match "Content-Type" header
body: JSON.stringify(data),
}); // end of respnose
try {
const newData = await response.json();
console.log(newData);
return newData;
}
catch(error) {
console.log("error", error);
}
} // end of postData
postData('/addName', {answer: 'evi'});
The traceback points to the line require('./routes')(app); (if I'm counting my line numbers correctly).
I think you could remove it, since you're doing app.use(require('./routes')); later.
Because you require the module with require('./routes')(app); then, in your module, you need to export a function that takes app as argument:
module.exports = app => {
...
return router;
}
So, the error is probably because you pass an argument to something that does not expect an argument.
I'm creating blog using node js and following this tutorial https://vegibit.com/node-js-blog-tutorial/ but now I stuck it gives me error on app.use('express-edge') here is my code
const path = require('path');
const expressEdge = require('express-edge');
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = new express();
mongoose.connect('mongodb://localhost:27017/node-blog', {
useNewUrlParser: true
})
.then(() => 'You are now connected to Mongo!')
.catch(err => console.error('Something went wrong', err))
app.use(express.static('public'));
app.use(expressEdge);
app.set('views', __dirname + '/views');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', (req, res) => {
res.render('index');
});
app.get('/posts/new', (req, res) => {
res.render('create')
});
app.post('/posts/store', (req, res) => {
console.log(req.body)
res.redirect('/')
});
app.listen(4000, () => {
console.log('App listening on port 4000')
});
and my error looks like
[nodemon] starting node index.js
C:\Users\91762\Desktop\Blog\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\91762\Desktop\Blog\node_modules\express\lib\application.js:210:11)
at Object. (C:\Users\91762\Desktop\Blog\index.js:16:5)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
at Module.load (internal/modules/cjs/loader.js:798:32)
at Function.Module._load (internal/modules/cjs/loader.js:711:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:1014:10)
at internal/main/run_main_module.js:17:11
[nodemon] app crashed - waiting for file changes before starting...
Maybe the tutorial is out of date, newest version of express-edge does not export edge engine as default export, the package exports a object what includes config, engine.
You can follow package document if your node version support object destructuring.
...
const { engine } = require('express-edge');
...
app.use(engine);
...
Or, just change a little in your code:
app.use(expressEdge.engine); // instead of app.use(expressEdge);
Use it like a handler is the best choice.
app.use(expressEdge.engine);
I am getting app.use() requires a middleware function error when using Express edge package in npm. I am using this - https://github.com/ecrmnn/express-edge
I followed and read the documentation but I can't seem to find what else does the function require
Here is the code.
const path = require('path');
const expressEdge = require('express-edge');
const express = require('express');
const app = new express()
app.use(express.static('public'));
app.use(expressEdge);
app.set('views', `${__dirname}/views`);
app.get('/', (req, res) => {
res.render('index');
})
app.get('/about', (req, res) => {
res.sendFile(path.reso0lve(__dirname, 'pages/about.html'))
})
app.get('/post', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/post.html'))
})
app.get('/contact', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/contact.html'))
})
app.listen( 4000, () => {
console.log('App has started')
})
Here is the error:
E:\NODE-JS-BLOG\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (E:\NODE-JS-BLOG\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (E:\NODE-JS-BLOG\index.js:11:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
app.use() requires a middleware function[nodemon] restarting due to changes...
Did you mean expressEdge.engine ?
const path = require('path');
const {engine} = require('express-edge');
const express = require('express');
const app = new express()
app.use(express.static('public'));
app.use(engine);
app.set('views', `${__dirname}/views`);
First time i have tried out to create a simple mean application.
I have followed the steps as per the below link
https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application#starting-our-node-application-packagejson
Finally i am getting the errors as
ReferenceError: mongoose is not defined
at Object.<anonymous> (C:\Users\Myname\Desktop\Mean sample\server.js:19:2)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
server.js
// modules =================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
// config files
var db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to our mongoDB database
// (uncomment after you enter in your own credentials in config/db.js)
mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('Magic happens on port ' + port);
// expose app
exports = module.exports = app;
How to fix it?
Can anyone please explain the steps to clear this issue
install mongoose
npm i mongoose --save
then import in your server.js file
var express = require('express');
var mongoose = require('mongoose') // import it
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');