简体   繁体   English

如何在生产中运行 node.js REST API 应用程序

[英]How to run a node.js REST API application in production

Ok, so right off the bat I feel a little dumb asking this question, but I'm a bit new to node.js apps so bear with me.好的,所以我觉得问这个问题有点愚蠢,但我对 node.js 应用程序有点陌生,所以请多多包涵。 I've written this REST API in node.js and it runs just fine on my local machine.我已经在 node.js 中写了这个 REST API 并且它在我的本地机器上运行得很好。 But, when I build it using webpack, I am not quite sure how it's supposed to actually run in the wild.但是,当我使用 webpack 构建它时,我不太确定它应该如何在野外实际运行。 Locally, I have a server.js using Express file that I start using node.在本地,我有一个使用我开始使用节点的 Express 文件的 server.js。 But how would I run the build version?但是我将如何运行构建版本? I'm sure the answer is obvious I'm just not seeing it.我确定答案很明显,我只是没有看到它。

My goal is to be able to run this on a subdomain on my shared hosting solution, so I'd have something like an example endpoint of https://myapi.mydomain.com/getAListOfSomething/我的目标是能够在我的共享主机解决方案的子域上运行它,所以我会有类似https://myapi.mydomain.com/getAListOfSomething/的示例端点

So bottom line - I wanna use Webpack to build my app, then deploy it somewhere and use it like a normal API.所以底线 - 我想使用 Webpack 来构建我的应用程序,然后将其部署在某个地方并像普通的 API 一样使用它。 I'm just not sure how to do about it.我只是不知道该怎么做。 With something like a React app, it's completely obvious to me (an index.html file with a script tag to my app, very simple) but with something like this I'm lost.对于像 React 应用程序这样的东西,这对我来说是完全显而易见的(一个 index.html 文件,我的应用程序带有一个脚本标签,非常简单)但是像这样的东西我迷路了。

So here's some code...所以这里有一些代码......

SERVER.JS服务器.JS

const routes = require('./routes/appRoutes.js');
const express = require('express');
const cors = require('cors');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const envPath = process.env.NODE_ENV !== 'production' ? `.env.${process.env.NODE_ENV}` : '.env';
const config = require('dotenv').config({path: envPath});

 bodyParser = require('body-parser');
 app = express();
 port = process.env.PORT || 3001;
 app.use(cors());
 app.listen(port);
 console.log(process.env.APP_NAME + ' started on port ' + port +' (yay!)');

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

 routes(app); //register the route

* WEBPACK.CONFIG.JS * * WEBPACK.CONFIG.JS *

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

const envPath = process.env.NODE_ENV !== 'production' ? `.env.${process.env.NODE_ENV}` : '.env';
const config = require('dotenv').config({path: envPath});


module.exports = (env) => {
    const isProduction = env==='production';

    return {
        entry: './routes/appRoutes.js',
        output: {
            path: path.join(__dirname,'public','dist'),
            filename: 'bundle.js'
        },
        target: 'node',
        node: {
            // Need this when working with express, otherwise the build fails
            __dirname: false,   // if you don't put this is, __dirname
            __filename: false,  // and __filename return blank or /
          },        
        externals: [nodeExternals()],
        module: {
            rules: [{
                loader: 'babel-loader',
                test: /\.js$/,
                exclude: /node_modules/
            }]
        },
        plugins: [
            new webpack.DefinePlugin({
             'process.env.APP_NAME': JSON.stringify(process.env.APP_NAME),
             'process.env.DB_HOST': JSON.stringify(process.env.DB_HOST),
             'process.env.DB_USERNAME': JSON.stringify(process.env.DB_USERNAME),
             'process.env.DB_PASSWORD': JSON.stringify(process.env.DB_PASSWORD),
             'process.env.DB_PASSWORD': JSON.stringify(process.env.DB_PASSWORD),
             'process.env.PORT': JSON.stringify(process.env.PORT)      
            })
         ],
        devtool: isProduction ? 'source-map' : 'inline-source-map',
        devServer: {
            contentBase: path.join(__dirname,'public'),
            port: 3300,
            historyApiFallback: true,
            publicPath: '/dist/'
        }    
    }
};  

PACKAGE.JSON PACKAGE.JSON

{
    "name": "spinder-api",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "build:dev": "webpack -p --env development",
        "build:prod": "webpack -p --env production",
        "dev-webpack": "webpack-dev-server --env development",
        "dev-server": "node app.js --env development"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@babel/cli": "^7.0.0",
        "@babel/core": "^7.0.0",
        "@babel/preset-env": "^7.0.0",
        "babel-watch": "^7.0.0",
        "bcrypt": "^3.0.4",
        "body-parser": "^1.18.3",
        "cors": "^2.8.5",
        "db-migrate-mysql": "^1.1.10",
        "dotenv": "^6.2.0",
        "express": "^4.16.4",
        "extract-text-webpack-plugin": "^3.0.2",
        "multer": "^1.4.2",
        "mysql": "^2.16.0",
        "type-of-is": "^3.5.1"
    },
    "devDependencies": {
        "@babel/core": "^7.6.2",
        "@babel/preset-env": "^7.6.2",
        "babel-loader": "^8.0.6",
        "html-loader": "^0.5.5",
        "html-webpack-plugin": "^3.2.0",
        "nodemon": "^1.18.10",
        "webpack": "^4.41.0",
        "webpack-cli": "^3.3.9",
        "webpack-dev-middleware": "^3.7.2",
        "webpack-dev-server": "^3.8.2",
        "webpack-hot-middleware": "^2.25.0",
        "webpack-node-externals": "^1.7.2"
    }
}

.ENV[.DEVELOPMENT] EXAMPLE (Note: I have a development and a production version, of course...) .ENV[.DEVELOPMENT] 示例(注意:我有一个开发和生产版本,当然......)

APP_NAME=spinder_api
DB_HOST=localhost
DB_USERNAME=db_username
DB_PASSWORD=my_strong_passwrod
DB_DATABASE=my_app_database
PORT=3300

in your webpack config you are building to public/dist/ there should be a bundle.js in there to run.在您正在构建到public/dist/的 webpack 配置中,应该有一个bundle.js可以运行。 Then simply node bundle.js然后只需node bundle.js

That seems like an odd location for a node project but it's easy to change.对于节点项目来说,这似乎是一个奇怪的位置,但很容易改变。

This question is very difficult to answer given that there are so many ways to deploy an application.鉴于部署应用程序的方法有很多,这个问题很难回答。 There are entities like Google Cloud Platform, Amazon Web Services, Microsoft Azure, ZEIT Now, Heroku, and many more.有 Google Cloud Platform、Amazon Web Services、Microsoft Azure、ZEIT Now、Heroku 等实体。 All of those have capabilities to add your endpoints and certificates for the domain that you have bought.所有这些都可以为您购买的域添加端点和证书。 Here's a few examples:这里有几个例子:

You can then use whatever endpoint it's configured for to access your app, API, etc.然后,您可以使用它配置的任何端点来访问您的应用程序,API 等。

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

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