Dan*_*aHa 2 javascript node.js express firebase firebase-hosting
我对 NodeJs 和 Firebase 很陌生。目前,我有一个带有 Express 的 NodeJs 项目和以下文件结构:
` + /root
+ /db
- user.js
+ /domain
- user.js
+ /node_modules
- ...
+ /routes
- routes.js
- sever.js
- config.json`
Run Code Online (Sandbox Code Playgroud)
我想在 Firebase 上托管它,但它向我添加了文件 index.html 和其他文件。如果我尝试使用 Cloud 函数,它会添加我 /functions 并在其中添加一个“index.js”文件,如下所示:
` + /root
+ /db
- user.js
+ /domain
- user.js
+ /functions
- index.js
+ /node_modules
- ...
+ /routes
- routes.js
- sever.js
- config.json
-firebase.json`
Run Code Online (Sandbox Code Playgroud)
我会尝试将我的 server.js 代码粘贴到 index.js 中,但是我从引用和丢失的包中得到错误。
这是我的 index.js 代码:
const functions = require('firebase-functions');
var express = require('express');
var bodyparser = require('body-parser');
var app = express();
// Use bodyParser to parse the parameters
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json({limit: '10mb'}));
// Call the routes
require('../routes/routes')(app);
exports.api = functions.https.onRequest(app);
Run Code Online (Sandbox Code Playgroud)
还有我的 routes.js 代码:
var userRoute = require('./users');
//Register routes and link to functions
module.exports = function(app){
app.post('/register', user.userRoute);
}
Run Code Online (Sandbox Code Playgroud)
我的 firebase.json
{
"hosting" : {
"public" : "public",
"rewrites" : [{
"source" : "/",
"function" : "api"
}]
}
}
Run Code Online (Sandbox Code Playgroud)
当我在本地运行时
firebase serve --only 功能
工作完美,但问题出现在我尝试部署的地方 任何想法?
有一些利基案例可以做到这一点。只要你必须这样做,这是可能的。它记录在使用 Cloud Functions 提供动态内容中。
基本上,您可以通过 firebase.json 在 Firebase Hosting 中配置重定向。像下面这样:
"rewrites": [ {
"source": "/myapi", "function": "myapi"
} ],
Run Code Online (Sandbox Code Playgroud)
然后,您index.js在 Firebase Functions 中配置您的文件以侦听该路径上的 HTTP 请求,例如:
app.get("/myapi", (request, response) => {
response.set("Cache-Control", "public, max-age=300, s-max-age=2629746");
var myparam = request.query.item;
return fetchSomethingFromFirestore(myparam).then((resp) => {
return response.render("template", {
myProperty: resp.valueForPugTemplate
});
});
});
app.use(function(err, req, res, next) {
return errorhandler(err, req, res, next);
});
const myapi = functions.https.onRequest((request, response) => {
if (!request.path) {
request.url = `/${request.url}`;
}
return app(request, response);
});
module.exports = {
myapi,
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3808 次 |
| 最近记录: |