我正在尝试在 nginx 上部署我的 Angular 项目的构建(其中也有一个 REST API),但是当我在 html 文件夹中加载 Dist 时,本地主机拒绝连接。
使用 npm run build 运行的本地主机确实会监听它,但我似乎无法破解如何将确切的输出部署到 Nginx Web 服务器上的代码。
(在我的 Angular 项目中)服务器.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')));
我是一名优秀的程序员,十分优秀!