【问题标题】:How to deploy express.js server to Netlify如何将 express.js 服务器部署到 Netlify
【发布时间】:2020-05-09 03:23:30
【问题描述】:

我正在尝试将 Vue.js、Node、Express、MongoDB (MEVN) 堆栈应用程序部署到 Netlify。我成功地将应用程序的前端部署到 Netlify,现在我正在尝试部署 express 服务器,基于以下 serverless-http 示例:https://github.com/neverendingqs/netlify-express/blob/master/express/server.js

我将我的服务器配置为包含 serverless-http 包:

server.js

const express = require('express');
const app = express();
const serverless = require('serverless-http');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');
const postRoute = require('./routes');

mongoose.connect(config.DB, { useNewUrlParser: true, useUnifiedTopology: true }).then(
  () => { console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use('/messages', postRoute);

app.use('/.netlify/functions/server', router);  // path must route to lambda
app.use('/', (req, res) => res.sendFile(path.join(__dirname, '../public/index.html')));


module.exports = app;
module.exports.handler = serverless(app);

routes.js

const express = require('express');
const postRoutes = express.Router();

// Require Post model in our routes module
let Post = require('./post.model');

// Defined store route
postRoutes.route('/add').post(function (req, res) {
  let post = new Post(req.body);
  post.save()
    .then(() => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(() => {
      res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
    Post.find(function(err, posts){
    if(err){
      res.json(err);
    }
    else {
      res.json(posts);
    }
  });
});

module.exports = postRoutes;

然后我将我的应用程序重新部署到 Netlify,但服务器似乎没有在 Netlify 中运行。此服务器位于我的 vue.js 应用程序的项目根目录中的一个文件夹中。我应该将服务器作为 Netlify 中的单独站点运行吗?如果没有,我应该怎么做才能让服务器在部署在 Netlify 时运行?

【问题讨论】:

  • 我只是评论说我目前遇到了同样的问题。希望有更好的文档!
  • 谁能告诉我/.netlify/functions/server里面有什么代码?

标签: javascript node.js express vue.js netlify


【解决方案1】:

我有一个类似的问题,只是我的服务器无法连接到本地路由,我的代码和你的代码之间的主要区别是我必须这样做

const router = express.Router()

然后用router.use()切换app.use()

就像我说的,那是因为本地主机说“无法获取 /* 定义的路径 */”

附:作为旁注,您不需要在最近的 express 中显式 bodyParser, express.json() 可以正常工作。

【讨论】:

    【解决方案2】:

    已经有一段时间了,但这里是。

    Netlify 托管用于 Jamstack,正如他们所说,即只有静态文件,在服务器上没有处理。我们的想法是利用其他机制来动态获取数据,例如托管在其他地方的 API,您可以直接从浏览器查询这些数据,或者在您构建网站时进行查询。

    实际上,您很可能不得不将您的 express.js 应用程序部署为 Netlify 函数。检查Netlify's blog post on running express apps on their functions

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2023-03-25
      • 2021-10-09
      • 1970-01-01
      • 2014-02-02
      • 2022-11-11
      相关资源
      最近更新 更多