简体   繁体   English

如何在Google Cloud Function上运行服务器-使用Node.js

[英]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). 我有在本地完美运行的NODE.js代码(127.0.0.1:CUSTOM_PORT)。 But now I would like to set it up to run it on Google Cloud Function. 但是现在我想对其进行设置以在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? 有人知道如何使用Google Cloud Functions设置正在运行的服务器吗? What port should I use and URL INSIDE THE NODE.JS ?? 我应该使用哪个端口以及NODE.JS内的URL? Or I do not need to use it at all as GCF already initially set up a server for me? 还是我根本不需要使用它,因为GCF最初已经为我设置了服务器?

GCF Provide trigger URL which can be hit, but it still does not work. GCF提供可以被触发的触发URL,但仍然无法使用。

Full function with out app.listen() 没有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. Google Cloud Functions具有最大的运行时间,然后该函数终止。 As of today this limit is 540 seconds. 截至今天,该限制为540秒。 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. HTTP触发器是一个例外,但这不适用于展示网站,但可用于操作。

There are companies that run their entire website using Cloud Functions, Cloud Datastore and Cloud Storage. 有些公司使用Cloud Functions,Cloud Datastore和Cloud Storage来运营整个网站。 The magic is using an API gateway product. 魔术使用的是API网关产品。 An API gateway provides the URL, www.example.com , that customers go to. API网关提供客户访问的URL www.example.com The API gateway then invokes Cloud Functions to handle the request. 然后,API网关调用Cloud Functions来处理请求。 You create similar mappings for each page on your serverless website to Cloud Functions. 您为无服务器网站上的每个页面创建到Cloud Functions的相似映射。

Many developers use Google App Engine to accomplish what you are trying to do. 许多开发人员使用Google App Engine完成您要完成的工作。 Very low cost and very easy to develop for. 成本极低,非常容易开发。 Another excellent Google product for you to consider is Google Firebase . 供您考虑的另一种出色的Google产品是Google Firebase Google has many other products that are not serverless such as Containers on Compute Engine and Kubernetes . Google还有许多其他非无服务器的产品,例如Compute Engine上的ContainerKubernetes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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