can any one fix this error of Node js and mongodb? - android

import jwt from 'jsonwebtoken';
import expressJwt from 'express-jwt';
const TOKENTIME = 60*60*24*90;
const SECRET = "W3 CHAT 4 FUN";
let authenticate = expressJwt({ secret: SECRET });
let generateAccessToken = (req, res, next) => {
req.token = req.token || {};
req.token = jwt.sign ({
id: req.user.id,
}, SECRET, {
expiresIn: TOKENTIME // 90 days
});
next();
}
let respond = (req, res) => {
res.status(200).json({
user: req.user.username,
token: req.token
});
}
module.exports = {
authenticate,
generateAccessToken,
respond
}
Error message:
var authenticate = (0, _expressJwt2.default)({ secret: SECRET });
^
TypeError: (0 , _expressJwt2.default) is not a function
at Object. (C:/Users/shoai/OneDrive/Desktop/mac-chat-api/src/middleware/authMiddleware.js:7:20)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at loader (C:\Users\shoai\OneDrive\Desktop\mac-chat-api\node_modules\babel-register\lib\node.js:144:5)
at Object.require.extensions. [as .js] (C:\Users\shoai\OneDrive\Desktop\mac-chat-api\node_modules\babel-register\lib\node.js:154:7)
at Module.load (node:internal/modules/cjs/loader:1089:32)
at Function.Module._load (node:internal/modules/cjs/loader:930:12)
at Module.require (node:internal/modules/cjs/loader:1113:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object. (C:/Users/shoai/OneDrive/Desktop/mac-chat-api/src/controller/user.js:6:1)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
just setting up mongodb and node js for local hosting

Related

Error 403 "The caller does not have permission"

I am trying to fetch data from dynamic links stastics API, and I have already sent bearer token inside the header. But it shows the error of permission denied.
final response = await http
.get(Uri.parse("https://patelmatch-api.herokuapp.com/getStat"));
final encodedLink = Uri.encodeComponent(currentAppuser.value.url!);
if (response.statusCode == 200) {
LinkStat linkStat = LinkStat.fromJson(jsonDecode(response.body));
print(linkStat.accessToken);
final responseData = await http.get(
Uri.parse(
"https://firebasedynamiclinks.googleapis.com/v1/${encodedLink}/linkStats?durationDays=7"),
headers: {'Authorization': 'Bearer ' + linkStat.accessToken!});
print(responseData.body);
} else {
print("Error");
}
isLoading.toggle();
index.js
const express = require('express')
const cors = require('cors')
const app = express()
app.use(express.json())
app.use(cors())
var { google } = require("googleapis");
const port = process.env.PORT || 5000
// Load the service account key JSON file.
var serviceAccount = require("./path/to/serviceAccountKey.json");
// Specify the required scope.
var scopes = [
"https://www.googleapis.com/auth/firebase"
];
app.get('/getStat', async(req, res) => {
var jwtClient = new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes
);
// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
if (error) {
console.log("Error making request to generate access token:", error);
} else if (tokens.access_token === null) {
console.log("Provided service account does not have permission to generate access tokens");
} else {
var accessToken = tokens.access_token;
console.log(tokens.access_token)
console.log(accessToken.length)
res.send({accessToken});
// Include the access token in the Authorization header.
}
});
})
app.listen(port, () => console.log("up & running on 4000"))
Here I have generated access token from nodejs and fetching data from flutter, but I am having error of permission. How to solve this issue?

"Server Error Problem" in Node.js API (for android to web server request)

"Server Error" in nodejs api (android to web server request)
I am a new node.js learner. I'm doing a project that user are registration by android application, and user details will go to web server. but when i send request to web server by API that time show "Server Error Problem". but when i send data by (postman row data) that time it works, but if i send by (postman form-data) that time it not work, and show "Server Error Problem".
In addition, I am using a shared linux Server supported by cpanel and CloudLinux.
-----------------------
index.js file
------------------------
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const verifyToken = require('./jwt/verify/verifytoken');
const mysql = require('mysql');
global.config = require('./jwt/config/config');
const extInfo = require('./info/extInfo');
const port = process.env.PORT || 3000;
const connection = mysql.createConnection({
host: "localhost",
user: “abcd”,
password: "123345",
database: “xyz”
});
var point = 0;
const app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(express.json());
app.use(bodyParser.urlencoded({extended : false}));
app.use(cors());
app.use('/api/v1', require('./api/v1'));
------------------------------------
api file (code)
---------------------------
const express = require('express');
const router = express.Router();
const mysql = require('mysql');
var error = ["error", "error", "error"];
const connection = mysql.createConnection({
host: "localhost",
user: “abcd”,
password: “12345”,
database: “xyz”
});
router.get('/login?', (req , res) => {
var studentdata = {
A: req.query.a,
B: req.query.b
}
connection.query(`Select Student_id from student where Mobile = ${a} and Password = ${b}`, (err, result, fields) => {
if (err) {
console.log("error");
res.send(error);
} else if (result.length < 1){
console.log("error");
res.send(err);
}
return res.send(result);
let Student_id = result[0].Student_id ;
connection.query(`SELECT * FROM B where A = ${A}`, (err1, result1, fields1) => {
if(err1){
res.send(err1);
} else if (result1.length < 1){
res.send(error);
}
res.send(result1);
});
});
});
router.post('/registration', (req , res) => {
let newStudent = {
a : req.body['a'],
b: req.body.b,
....
c: req.body.c
}
connection.query(`SELECT * FROM d1 where Mobile = ${a}`, (err, result , fields) => {
if(err) {
return res.send("Server Error");
} else if (result.length > 0) {
return res.send("wrong phone");
}
connection.query(`INSERT INTO d1 (Student_name, School , ..... , Password ) VALUES ('${newStudent.student_name}', ..... , '${newStudent.student_password}')`, (err1, result1, fields1) => {
if(err1) {
return res.send(error);
} else if (result1.length > 0) {
return res.send("wrong phone");
}
let insertId = result1.insertId;
// Create Score table Account
connection.query(`INSERT INTO d2( A ) VALUES ('${insertId}')`, (err2, result2, fields) => {
if (err2) {
return res.send(err2);
}
return res.send("Registration Successful");
});
})
});
});
router.get('*', (req , res) => {
res.send({"info" : "Nothing Found"});
});
module.exports = router ;

node.js referenceError variable is not defined

I am trying to implement device groups in my node.js file to trigger notifications.
I want to get the token_id and create a notification_key for the device groups for a single user.
but i am getting the error as.
ReferenceError: options is not defined
at Object.<anonymous> (D:\SweExpress\functions\index.js:13:9)
at Module._compile (internal/modules/cjs/loader.js:678:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
at C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:21:11
at Object.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:61:3)
and my index.js file is.
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
var request = require('request');
admin.initializeApp();
var headers = {
'Authorization': 'key = my service account key here',
'project_id': 'server_id',
'Content-Type': 'application/json'
}
request(options, function (error, response, body) {
console.log(body)
})
exports.sendNotification = functions.firestore.document("Users/ {user_id}/Notifications/{notification_id}").onWrite((change,context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
return admin.firestore().collection("Users").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult => {
const from_user_id = queryResult.data().from;
const from_message = queryResult.data().message;
const from_data = admin.firestore().collection("Users").doc(from_user_id).get();
const to_data = admin.firestore().collection("Users").doc(user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const from_name = result[0].data().name;
const to_name = result[1].data().name;
const token_id = result[1].data().token_id;
var options = {
url: 'https://android.googleapis.com/gcm/notification',
method: 'POST',
headers: headers,
json: {'operation': 'create',
'notification_key_name': 'you#example.com',
'registration_ids': [token_id]}
}
request(options, function (error, response, body) {
console.log(body)
})
var notificationKey = body;
const payload = {
notification: {
title: "Notification From: " + from_name,
body : from_message,
icon : "notification.png",
sound: "orion.mp3"
}
};
return admin.messaging().sendToDeviceGroup(notificationKey,payload).then(result => {
var c = console.log("Notification sent ");
return c;
});
});
});
});
I am new to node.js as well.
Secondly, is my index.js file correct? or I am doing something wrong?.
Without initializing variable named option, your are passing it as a parameter for the request. Thats why you are getting following error ReferenceError: options is not defined. Here I commented the unused part. checkout this snippet now
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
var request = require('request');
admin.initializeApp();
var headers = {
'Authorization': 'key = my service account key here',
'project_id': 'server_id',
'Content-Type': 'application/json'
}
/* Code which causes error
request(options, function (error, response, body) {
console.log(body)
})*/
exports.sendNotification = functions.firestore.document("Users/ {user_id}/Notifications/{notification_id}").onWrite((change,context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
return admin.firestore().collection("Users").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult => {
const from_user_id = queryResult.data().from;
const from_message = queryResult.data().message;
const from_data = admin.firestore().collection("Users").doc(from_user_id).get();
const to_data = admin.firestore().collection("Users").doc(user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const from_name = result[0].data().name;
const to_name = result[1].data().name;
const token_id = result[1].data().token_id;
var options = {
url: 'https://android.googleapis.com/gcm/notification',
method: 'POST',
headers: headers,
json: {'operation': 'create',
'notification_key_name': 'you#example.com',
'registration_ids': [token_id]}
}
request(options, function (error, response, body) {
console.log(body)
})
var notificationKey = body;
const payload = {
notification: {
title: "Notification From: " + from_name,
body : from_message,
icon : "notification.png",
sound: "orion.mp3"
}
};
return admin.messaging().sendToDeviceGroup(notificationKey,payload).then(result => {
var c = console.log("Notification sent ");
return c;
});
});
});
});
Your options object is defined after its first use:
request(options, function (error, response, body) {
console.log(body)
})
Define
var options = { ...
before it is used in
request(options ...
Hope that helps :)

How to connect the React Native app with Loopback API Explorer?

I have created a React Native app which can connect my own API but if I want to connect to the Loopback API, it always got some problem with the authentication, may I know how to connect the React Native app with the Loopback API? Previously, this is my own API:
var API_URL = 'http://192.168.10.130:8000/api';
exports.SIGNIN_URL = `${API_URL}/auth/token/`;
exports.TODOS_URL = (token) => `${API_URL}/workrequests/`;
But after I change to the Loopback API it cannot get the token from it so I also want to know how to get the access token from it and act it as an authentication token, thank you.
var API_URL = 'http://localhost:3000/api';
exports.SIGNIN_URL = `${API_URL}/Users/login/`;
exports.TODOS_URL = (token) => `${API_URL}/WorkRequests/`;
//AuthAction.js
import axios from 'axios';
import Keychain from 'react-native-keychain';
import {SIGNIN_URL} from '../api';
import {addAlert} from './alertsActions';
exports.loginUser = (username, password) => {
return function(dispatch) {
return axios.post(SIGNIN_URL, {username, password}).then((response) => {
var {token} = response.data;
console.log(token);
Keychain.setGenericPassword(username, token)
.then(function() {
dispatch(addAlert(token));
dispatch(authUser(token));
}).catch((error) => {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
});
}).catch((error) => {
dispatch(addAlert("Could not sign in."));
});
}
}
authUser = (token) => {
return {
type: 'AUTH_USER',
token
}
}
exports.unauthUser = {
type: 'UNAUTH_USER'
}

react-native upload pictures on android

I have a react-native app on Android and a backend server written in NodeJS + Express and I'm using multer to handle file uploads.
const multer = require('multer');
const mime = require('mime');
const crypto = require('crypto');
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, config.uploads),
filename: (req, file, cb) => {
crypto.pseudoRandomBytes(16, (err, raw) => {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
});
}
});
const upload = multer({ storage });
const Router = require('express').Router;
const controller = require('./upload.controller');
const router = new Router();
const auth = require('./../../auth/auth.service');
router.post('/', [auth.isAuthenticated(), upload.any()], controller.create);
module.exports = router;
And on my react-native app I try to do like this:
ImagePicker.launchCamera(options, image => {
let { uri } = image
const API_URL = 'http://192.168.1.2:9000/api/uploads'
var form = new FormData();
form.append("FormData", true)
form.append("access_token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU3YjgyZGQ2MTEwZDcwYmEwYjUxZjM5YyIsImlzTWVkaWMiOnRydWUsImlhdCI6MTQ3MTY4ODE1MiwiZXhwIjoxNDcxNzA2MTUyfQ.gPeql5g66Am4Txl1WqnbvOWJaD8srTK_6vihOJ6kFbY")
form.append("Content-Type", "image/jpg")
form.append('image', uri)
fetch(API_URL, {body: form, mode: "FormData", method: "post", headers: {"Content-Type": "multipart/form-data"}})
.then((response) => console.log(response))
.catch((error) => {
console.log("ERROR " + error)
})
.then((responseData) => {
console.log("Succes "+ responseData)
})
.done();
})
But when I try to upload I recive the following error
multipart body must have at least one part
I am doing something wrong?
Does anybody knows a better solution to do this?
Fetch may not support Blob and FormData at this moment, but you can use XMLHttpRequest polyfill instead.
let xhr = new XMLHttpRequest()
xhr.open('post', `http://myserver.com/upload-form`)
xhr.send(form)
xhr.onerror = function(e) {
console.log('err', e)
}
xhr.onreadystatechange = function() {
if(this.readyState === this.DONE) {
console.log(this.response)
}
}

Categories

Resources