首页 > 解决方案 > 在 Nginx for Windows 上部署 Angular 构建

问题描述

我正在尝试在 nginx 上部署我的 Angular 项目的构建(其中也有一个 REST API),但是当我在 html 文件夹中加载 Dist 时,本地主机拒绝连接。

使用 npm run build 运行的 localhost 确实会听它,但我似乎破解了如何将确切的输出部署到 Nginx 网络服务器的代码。

(在我的 Angular 项目中)server.js

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

// Get our API routes
const api = require('./server/routes/api');

const app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/ProjectName/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

服务器/路由/api(用于测试)

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

// declare axios for making http requests
const axios = require('axios');
const API = 'https://jsonplaceholder.typicode.com';

/* GET api listing. */
router.get('/', (req, res) => {
  res.send('api works');
});

// Get all posts
router.get('/posts', (req, res) => {
  // Get posts from the mock api
  // This should ideally be replaced with a service that connects to MongoDB
  axios.get(`${API}/posts`)
    .then(posts => {
      res.status(200).json(posts.data);
    })
    .catch(error => {
      res.status(500).send(error)
    });
});

module.exports = router;

package.json 脚本

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxyConfig.json",
    "build": "ng build && node server.js",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }

proxyConfig.json

{
    "/api": {
      "target": "http://localhost:3000",
      "secure": false,
      "changeOrigin": true
    }
  }

nginx.conf

server {
        listen       8080;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html/dist/ProjectName;
            index  index.html index.htm;
        }
    location /api {
                 proxy_pass   http://localhost:3000;

标签: node.jsangularnginxproxy

解决方案


换行

app.use(express.static(path.join(__dirname, 'dist')));

app.use(express.static(path.join(__dirname, 'dist/ProjectName')));

推荐阅读