问题
I generated a demo express server using these steps:
npm install -g express-generator
express myExpressApp --view pug
Needless to say, the app runs fine on my local machine (npm start
)
I then pushed the code to Cloud Source Repositories
Then deploy to Google Cloud Functions through their web app
What am I missing?
Source codes of my generated demo app:
/myExpressApp/app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
/myExpressApp/routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Final updates
I added the following as suggested by Abrar Hossain app.js
//...
module.exports = app;
exports.app = functions.http.onRequest(app);
module.exports = { app };
package.json
"scripts": {
"start": "functions-framework --target=company"
},
"dependencies": {
"@google-cloud/functions-framework": "^1.7.1",
But the issue persists
Entry point is set as "app"
回答1:
In short, during deployment, you have to specify the name of the JS function you want to use as GCP Cloud function, it is specified --entry-point
flag. More information here (pls, do look at the flags sections). app
in your case. If you provide the deployment script, I can point you to the exact spot
Long answer - the common misconception is that a GCP Cloud functions = Express app. It is not. Although under the hood they might use express and you might event request certain behavior via configuration. In reality, for GCP it is just a JS function, nothing more or less. No routers or anything like that. If you want to test it locally, use Functions Framework. You can get further details in my post
来源:https://stackoverflow.com/questions/65600181/google-cloud-functions-build-failed-function-js-does-not-exist-error-id-7485c