У меня проблема с правильной загрузкой ресурсов в нашей текущей настройке. Мы используем NGINX, Node 8.11, angular 6
В общем, мне пришлось выполнить некоторый синтаксический анализ запроса, поступающего на наш узел server.js, чтобы файлы загружались правильно для angular.
Вот настройка типичного приложения под названием Heroes:
Nginx
location /heroes/ {
proxy_pass
http://unix:///myapps/tmp/node.sock;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header X-UA-Compatible "IE=edge";
}
Узел Server.js
...
//==============================================================
// Point static path to dist
//=================================================================
app.use(express.static(__dirname + '/dist/'));
// set the static files location for the angular build
...
Node Server.js - создать список разрешенных расширений
...
// Allowed extensions list can be extended depending on your own needs
const allowedExt = [
'.js',
'.ico',
'.css',
'.png',
'.jpg',
'.woff2',
'.woff',
'.ttf',
'.svg',
'.map',
'.otf',
'.eot',
'.gif'
];
...
Node Server.js - направляет файлы на угловое расстояние
...
// Redirect all the other requests
// TODO: This part is a hack.
//The main issue is express not serving up the static assets
app.get('*', (req, res) => {
if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
var iFileStart=req.url.lastIndexOf("/");
var sFile=req.url.substring(iFileStart+1);
res.sendFile(path.resolve('dist/'+sFile));
} else {
res.sendFile(path.resolve('dist/index.html'));
}
});
...
Угловой index.html
...
<base href = "/heroes/">
...
При такой настройке мои приложения в основном работают. Мне пришлось добавить в него еще несколько кладжей для решения некоторых других проблем.
Проблема в том, что до этого взлома экспресс или моя установка nginx неправильно перенаправляли запрос на активы. Я почти уверен, что мне не нужно проверять расширения файлов и направлять их по-другому.
Если я изменю файл Node Server.js на это:
app.get('*', (req, res) => {
res.sendFile(path.resolve('dist/index.html'));
});
Затем я получаю в браузерах такую ошибку: Файлы JS обслуживаются как html?
Кажется, что файлы можно найти, но они не обрабатываются как файлы JS.
Какие-либо предложения?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Хорошо, я решил свою проблему.
Пришлось отредактировать следующее:
NGINX:
location /heroes/ {
root /app/mydir/heroes/dist <--- added this
proxy_pass http://unix:///myapps/tmp/node.sock;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header X-UA-Compatible "IE=edge";
}
Server.js
...
//======================================================================
// Point static path to dist - false will cause a 404 if not found
//========================================================================
app.use(function (req, res, next) {
next();
}, express.static(__dirname+'/dist',{fallthrough:true}));
...
....
app.get('*', (req, res) => {
res.sendFile(path.resolve('dist/heores/index.html'));
});
...
angular.json
"outputPath": "dist/heroes",
Теперь все работает. Надеюсь, другие сочтут это полезным.