简体   繁体   中英

How to run server on Google Cloud Function - with Node.js

I have NODE.js code which works perfectly locally (127.0.0.1:CUSTOM_PORT). But now I would like to set it up to run it on Google Cloud Function.

This is the code which I'm using to run code locally:

function connect_to_server() {
    const PORT = process.env.PORT || 8080;
    app.listen(PORT,'127.0.0.1',function () {
        console.log('---> SERVER IS RUNNNG <---')
    })
}

Does someone know the way to set a running server with Google Cloud Functions? What port should I use and URL INSIDE THE NODE.JS ?? Or I do not need to use it at all as GCF already initially set up a server for me?

GCF Provide trigger URL which can be hit, but it still does not work.

Full function with out app.listen()

// CONFIGURATION
const express = require('express')
const app = express()
const config = require('./config')
const bodyParser = require('body-parser')
const moment = require('moment')
const sql = require("mssql")
const jwt = require('jwt-simple')
const compression = require('compression')


function token(token) {
    var secret = Buffer.from('xxx', 'hex')
    return jwt.decode(token, secret)
}

function sql_puller(res, req) {
    sql.connect(config, function (err) {
        if (err) {
            console.log(err)
            res.send(err.code)
        }

        const request = new sql.PreparedStatement()

        const {
            x
        } = req.body

        let newProps = {}

        x.forEach(filters => {
            newProps[filters.x] = filters.x
        })

        const isValidInput = validateInput(x, x, x, res)

        if (!isValidInput) {
            return
        }

        request.input('1', sql.VarChar(1))
        request.input('2', sql.VarChar(1))
        request.input('3', sql.VarChar(1))

        sqlQuery = `XXXXXX`

        request.prepare(sqlQuery, err => {
            if (err) {
                console.log(err)
                res.send(err.code)
                return
            }
            request.execute({
                iso: x,
                start: x,
                end: x
            }, (err, recordset) => {
                request.unprepare(err => {
                    if (err) {
                        console.log(err)
                        res.send(err.code)
                        return
                    }
                })
                if (err) {
                    console.log(err)
                    res.send(err.code)
                    return
                }

                res.json(recordset)
                sql.close()
            })
        })
    })



    sql.on('close', function (err) {
        console.log('SQL Connection Closed.', err)
    })

    sql.on('error', function (err) {
        sql.close()
        console.log('SQL error occurred.', err)
    })
}


exports.main = function main() {
    app.use(compression())
    app.use(bodyParser.json())
    app.post('/', function (req, res) {

        try {

            res.setHeader('Cache-Control', 'public, max-age=3600')
            var decodedToken = token(req.body['Token'])
            console.log(req.body)
            console.log('Successefully connected - token accepted')
            // connect to your databas

            if (decodedToken == "XXXXXX") {
                sql_puller(res, req)
            } else {
                console.log('Incorrect Token')
            }

        } catch (err) {
            if (err) {
                console.log(err)
                res.send('Invalid Token')
                return
            }
        }
    })
}

You cannot the way you have designed it. Google Cloud Functions has a maximum runtime and then the function is terminated. As of today this limit is 540 seconds. Cloud Functions are invoked by an outside process, Cloud Functions do not wait for someone to connect to them (eg they don't listen, they are not asleep). The exception is HTTP Trigger, but this is not usable to present a website, but can be usable for actions.

There are companies that run their entire website using Cloud Functions, Cloud Datastore and Cloud Storage. The magic is using an API gateway product. An API gateway provides the URL, www.example.com , that customers go to. The API gateway then invokes Cloud Functions to handle the request. You create similar mappings for each page on your serverless website to Cloud Functions.

Many developers use Google App Engine to accomplish what you are trying to do. Very low cost and very easy to develop for. Another excellent Google product for you to consider is Google Firebase . Google has many other products that are not serverless such as Containers on Compute Engine and Kubernetes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM