node.js - 在 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;
解决方案
换行
app.use(express.static(path.join(__dirname, 'dist')));
和
app.use(express.static(path.join(__dirname, 'dist/ProjectName')));
推荐阅读
- javascript - 需要参考有关使用 push 的三元运算符的文档
- fortran - 什么是 BLAS 中的 TDOT 子程序?
- c# - Xamarin.Mac 安全文本字段通过输入 Enter 键移动焦点
- java - 我希望玩家在下一个场景按钮出现之前正确匹配 5 个项目
- python - 从另一个 DataFrame 中的选定数据创建一个新的 DataFrame
- flutter - “添加到应用程序”的问题:无法使用配置启动引擎
- c++ - Eigen C++:将 2D 极坐标转换为笛卡尔坐标的最佳方法
- pyinstaller - Pyinstaller-spacy:“OSError:[E050] 找不到模型 'es_core_news_sm'。它似乎不是 Python 包或数据目录的有效路径。”
- typescript - 是否可以让 Storybook.js 使用非常大的自动生成的 Typescript 文件(>200 个类)?
- laravel - 如何在某个计数后跳过一个循环到下一个循环,并在下一个循环中达到某个计数后再次返回