here iam using a cloud functions to create users i am using a express module when i try to deploy this code it deploying to cloud funtions with message that Error : Funtions did not deploy properly
const express = require('express');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const serviceaccount = require('./ServiceAccountKey.json');
const app = express();
admin.initializeApp({
credential: admin.credential.cert(serviceaccount)
});
app.post('/',(req,res)=>{
if(req.method!== 'POST'){
res.status(400).send("what are u trying baby");
return;
}
admin.auth().createUser({
email:req.body.email,
password: req.body.pass,
}).then(function(userRecord){
res.send({'uid': userRecord.uid});
return;
}).catch(function(error){
res.send({'error': 'Try COrrect one baby'});
return;
});
return;
});
exports.register = funtions.Https.onRequest(app);
when i add this at end
module.exports = {
app
}
it showing funtion deployed but its not showing in cloud functions dashboard
what wrong am i doing here
here is the error what ima getting i cnat get whAT THE error is
⚠ functions[register(us-central1)]: Deployment error.
Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:476:15)
at Function.Module._load (module.js:424:25)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/index.js:1:79)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
Functions deploy had errors with the following functions:
register
You code never uses the firebase-functions modules to declare a Cloud Function. Your functions variable is going unused. You can't just export any function an expect it to run - it has to be built by the SDK.
If you have an express app to deploy, you need to export it via an HTTP type function:
exports.app = functions.https.onRequest(app);
First, I think you need to change the endpoint of the url. Don't just put '/'. Maybe like '/user/create'.
app.post('/user/create',(req,res)=>{
if(req.method!== 'POST'){
res.status(400).send("what are u trying baby");
return;
}
admin.auth().createUser({
email:req.body.email,
password: req.body.pass,
}).then(function(userRecord){
res.send({'uid': userRecord.uid});
return;
}).catch(function(error){
res.send({'error': 'Try COrrect one baby'});
return;
});
return;
});
exports.register = funtions.Https.onRequest(app);
And in your firebase.json you should rewrite the url :
{
"functions": {
...
},
"hosting": {
"public": "public",
"rewrites": [
{
"source": "/user/create",
"function": "register"
}
]
}
}
For more explanation, you can follow this tutorial.
Related
I'm running into an issue where I try to require a .jpg image.
When Googling I thought it had something to do with Jest but now when I start from a clean project, not having Jest as a dependency I get the same error.
What can be the issue?
This is the files I'm trying to run
server.js
// Import express framework
const express = require('express')
// Import routes
const visionAiRouter = require('./routes/vision-ai-route')
// Setup default port
const PORT = process.env.PORT || 4000
// Create express app
const app = express()
// Vision AI Route
app.use('/ai', visionAiRouter)
// Implement route for errors
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
// Start express app
app.listen(PORT, function() {
console.log(`Server is running on: ${PORT}`)
})
vision-ai-route.js
// Import
const express = require('express')
const visionAi = require('../controllers/vision-ai-controller')
// Create express router
const router = express.Router()
router.get('/', visionAi.labelDetection)
// Export
module.exports = router
vision-ai-controller.js
// Assets
const cat = require('./../data/cat.jpg')
// Create controller for GET request to '/users/all'
exports.labelDetection = async (req, res) => {
// Imports the Google Cloud client library
const vision = require('#google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
const [result] = await client.labelDetection(cat);
const labels = result.labelAnnotations;
const stringify = JSON.stringify(labels);
await res.json(stringify)
}
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"#google-cloud/vision": "^2.1.1",
"express": "^4.17.1",
"nodemon": "^2.0.4"
},
"devDependencies": {},
"scripts": {
"start": "nodemon server.js"
},
"author": "",
"license": "ISC"
}
Stacktrace
/Users/kod/Desktop/Code/Private/vision-ai/test/data/cat.jpg:1
����
^
SyntaxError: Invalid or unexpected token
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787: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 Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/Users/kod/Desktop/Code/Private/vision-ai/test/controllers/vision-ai-controller.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
You can't require a non-code file as require is meant to load executable code. The correct equivalent would be const cat = fs.readFileSync('./test/data/cat.jpg').
I'm currently working on a POC to implement Apollo Federation gateway in and NodeJS + express application. Up until now, I haven't really encountered any example on how to properly do it.
So far, I encounter a problem where the ApolloServer module doesn't recognize an instance of ApolloGateway from #apollo/gateway. I'm using ApolloServer instance as a wrapper of the gateway's instance as shown from the tutorial: https://www.apollographql.com/docs/apollo-server/federation/implementing/#defining-the-gateway. However, I ran into a problem when calling the server.applyMiddleWare() in my express app. I came across the example from https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-express#express
to be specific here is a snippet of the error log:
$ node --use_strict ./bin/www
/Users/evanlee/dev/federation-gateway/node_modules/loglevel-debug/index.js:32
target[k] = attr.bind ? attr.bind(k) : attr;
^
TypeError: Cannot assign to read only property 'name' of function 'function() {
return log.debug.apply(this, arguments);
}'
at /Users/evanlee/dev/federation-gateway/node_modules/loglevel-debug/index.js:32:15
at Array.forEach (<anonymous>)
at composit (/Users/evanlee/dev/federation-gateway/node_modules/loglevel-debug/index.js:30:20)
at Object.loglevelDebug [as default] (/Users/evanlee/dev/federation-gateway/node_modules/loglevel-debug/index.js:201:3)
at new ApolloGateway (/Users/evanlee/dev/federation-gateway/node_modules/#apollo/gateway/dist/index.js:101:33)
at Object.<anonymous> (/Users/evanlee/dev/federation-gateway/app.js:21:12)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
error Command failed with exit code 1.
and here is how I'm trying to integrate the ApolloServer to my express app:
const { ApolloServer } = require('apollo-server');
const { ApolloGateway } = require('#apollo/gateway');
const app = express();
// Apollo Server and Gateway definition
const server = new ApolloServer({
gateway: new ApolloGateway({
debug: true,
serviceList: [
{ name: 'base-app', url: 'http://localhost:4001/graphql' },
]
}),
subscriptions: false,
});
server.applyMiddleware({ app, path: '/graphql' });
really appreciate the help!
It's working for me using latest. However, I'm not using debug: true try without?
I have a simple REST API using MEAN. It's hosted on Heroku, and everything works well there. However, if I try to run it on localhost I get the following error:
TypeError: Parameter "url" must be a string, not undefined
at Url.parse (url.js:81:11)
at Object.urlParse [as parse] (url.js:75:5)
at module.exports (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/url_parser.js:15:23)
at connect (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/mongo_client.js:403:16)
at Function.MongoClient.connect (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/mongo_client.js:227:3)
at Object.<anonymous> (/Users/ricardotaboada/Desktop/sbackend/server.js:15:21)
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)
Any idea what's going on? Thanks very much.
EDIT: Here is the code that connects to Mongo:
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
sbrdcontroller = new controller(database);
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || 3000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
Hard to say without seeing some code.
That said, from the error message it sounds like you're not passing a valid URL to connect to your mongodb.
EDIT:
Right, so based on your code, check the value of process.env.MONGODB_URI. You can do that from your heroku account or cli, or by console.log, but I'm betting it's not set on your heroku app. Depending on the Mongo addin you use, they use different environment variable names.
process.env.MONGODB_URI is undefined in your local environment which is why the error is being thrown.
Add this code before the database connection code:
var development = process.env.NODE_ENV !== 'production';
var mongo_url;
if (development) {
mongo_url = 'mongodb://localhost:27017/mydb';
}
else {
mongo_url = process.env.MONGODB_URI;
}
Then change:
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
To:
mongodb.MongoClient.connect(mongo_url, function (err, database) {
Assuming your local Mongo database port was not changed, the local URL with port 27017 should work fine.
Now your code should work fine in both development and production.
Maybe dotenv module will be useful for you:
https://www.npmjs.com/package/dotenv
I have a simple webpack with react hotloader & express setup and working. I'm trying to add an external node module that will register a sub router for some services. For some reason, doing so causes a strange exception (see below).
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');
var app = express();
var router = express.Router();
var mod = require("my-module");
mod.registerServices(router); // <-- adds routes to the router
app.use("/api/v1*", router); // <-- This line causes the error
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
The Exception:
$ node server.js
/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51
throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');
^
Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
at Object.proxyReactComponents [as default] (/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51:11)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/components/simple.js:25:60)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/containers/CompanyLocationPage.js:13:25)
at Module._compile (module.js:434:26)
UPDATE
Turns out that removing this from .babelrc where I have some react transforms enabled and subsequently removing all of the web pack hotloader plugins & middleware gets the router working again.
{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}
Try this solution: don't use babel-plugin-react-transform in .babelrc, use config in webpack.config.js
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
include: path.join(__dirname, 'src'),
query: {
plugins: [
["react-transform", {
transforms: [{
transform: "react-transform-hmr",
imports: ["react"],
locals: ["module"]
}]
}]
]
}
}
]
}
Details:
https://github.com/gaearon/babel-plugin-react-transform/issues/62
https://github.com/gaearon/react-transform-hmr/issues/5
I got a SailsJS application in which I need to reference a htpasswd file that is located at the root of my project:
var auth = require('http-auth');
var basic = auth.basic({
authRealm: "Admin Panel",
authFile: 'htpasswd', // <-- how do I specify the path to this file ?
authType: 'basic'
});
module.exports = function(req, res, next) {
basic.apply(req, res, function(username) {
if(!username) {
return res.serverError(403, 'You are not authorized');
}
next();
})(req, res);
}
I have tried using:
authFile: '/htpasswd'
As well as:
authFile: '~/htpasswd'
Neither works.
Update
Hurmm....it seems like it's not the code that has error, somehow, my Sailsjs application can't find the htpasswd module.
I did do:
sudo npm install -g htpasswd
I also used htpasswd command line to generate the htpasswd file...somethings wrong with my project setup...
My console error says:
Error: Cannot find module 'htpasswd'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/MacUser/SailsProjects/SecurePanel/node_modules/http-auth/gensrc/auth/basic.js:11:14)
Use the native __dirname variable which evaluates to the path of the current file.
See what it is using console.log(__dirname). And then you could do:
var basic = auth.basic({
realm: "Admin Panel",
file: __dirname + "/path_from_current_file_to/htpasswd"
});
So if the root was a folder up from this the folder that this script is in, you could do
__dirname + "/../htpasswd"