Для тестовых целей я запускаю локальный веб-сервер Apache, и я настраиваю приложение node.js, прослушивающее порт 8888, служащий в качестве препроцессора изображения, но, к сожалению, Я испытываю проблемы, как описано ниже.Локальный тест: не удается получить ресурс с помощью http: // localhost: 8888
Узел app.js работает в каталоге корневой веб:
'use strict';
let express= require('express')
,multer = require('multer')
,upload = multer()
,app = express()
//Import imgProcessor module which we would implement later
,imgProc = require('./imgProcessor');
app.get ('/', (req, res, next)=>{
res.sendFile(__dirname+'/appmain.html');
});
app.post('/uploadImg', upload.array('pics'),
(req, res, next)=>{
//Call the convertImgs method and pass the image files as its argument
imgProc.convertImgs(req.files).then(
(imageStringArray)=>{
//After all image processing finished, send the base64 image string to client
res.json(imageStringArray)})});
app.listen(8888,()=>{
console.log('Hosted on Port 8888')});
appmain.html страница находится в том же корневой веб-каталог:
<html>
<head>
<title>Upload Image Demo</title>
<link rel="shortcut icon" href="">
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/materialize-css/dist/js/materialize.min.js"></script>
<link rel="stylesheet" href="node_modules/materialize-css/dist/css/materialize.min.css">
</head>
<body class="container">
<div class="row">
<form id="form1" class="col m4 offset-m4" action="/uploadImg" enctype="multipart/form-data" method="post">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file" multiple="" accept="image/jpeg,png" name="pics">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more files">
</div>
</div>
<div class="input-field">
<button type="submit" class="waves-effect waves-light btn">Submit</button>
</div>
<div class="progress" style="display:none">
<div class="indeterminate"></div>
</div>
</form>
</div>
<div class="row img-preview"></div>
<script>
$(function(){
$('#form1').on('submit', function(event){
event.preventDefault();
var data = new FormData(this);
$.each(
$('input[name="pics"]')[0].files,
function(i, file){
data.append('file-'+i, file);
});
$('.progress').css({
display:'block'
});
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:data,
cache:false,
contentType: false,
processData: false,
success:function(data){
for(var i=0;i<data.length;i++){
var template =
'<div class="col m4">
<div class="card">
<div class="card-image">
<img src="'
+ data[i]
+ '"></div></div></div>';
$('.img-preview').append(template);
}
$('.progress').css({
display:'none'
});
},
error: function(err){
$('.progress').css({
display:'none'
});
}
});
})
})
</script>
</body>
</html>
Когда я используйте URL-адрес http://localhost:8888
, в браузере загружается страница html (т. е. я могу видеть кнопки и поля ввода формы), но ресурсы, запрошенные в <script>
(например: node_modules/jquery/dist/jquery.min.js
или node_modules/materialize-css/dist/js/materialize.min.js
) не загружены. Точно так же страница не может извлечь выгоду из разгруженной таблицы стилей CSS.
Как и наоборот, если я пытаюсь использовать URL-адрес http://localhost/appmain.html
, страница загружается как ожидалось (я имею в виду: с правильными ресурсами и CSS).
Кажется, что мой веб-сервер Apache не может обслуживать ресурсы при обработке номера порта внутри URL-адреса. Как я могу это решить?
EDIT Только для упрощения: let'say узел app2.js прослушивает порт 8888 и имеет только метод (получить), отправляющие к клиенту «Hello World!» страница app2main.html. Нет файлов для обслуживания. На странице app2main.html нужно только загрузить несколько сценариев Javascript и таблицу стилей CSS.
приложение2.js 'use strict';
let express= require('express')
,app = express();
app.get ('/', (req, res, next)=>{
res.sendFile(__dirname+'/app2main.html');
});
app.listen(8888,()=>{
console.log('Hosted on Port 8888')});
app2main.html
<html>
<head>
<title>Upload Image Demo</title>
<link rel="shortcut icon" href="">
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script
src="node_modules/materialize-css/dist/js/materialize.min.js"></script>
<link rel="stylesheet"
href="node_modules/materialize-css/dist/css/materialize.min.css">
</head>
<body class="container">
<h2> Hello World! </h2>
</body>
</html>
При доступе к URL http://localhost:8888
'Hello World!' появляется сообщение, но я получаю следующее сообщение об ошибке (Запись видна при осмотре страницы):
http://localhost:8888/node_modules/jquery/dist/jquery.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8888/node_modules/materialize-css/dist/js/materialize.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8888/node_modules/materialize-css/dist/css/materialize.min.css Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8888/node_modules/materialize-css/dist/css/materialize.min.css Failed to load resource: the server responded with a status of 404 (Not Found)
Вместо этого я не получаю ошибку (и ожидаемый стиль) при доступе к URL http://localhost/app2main.html
Вы не можете использовать случайные файлы из любого старого места в веб-приложении - вам нужно настроить его для работы со статическими файлами. Лично я бы не служил им из ваших модулей узлов, но почему бы не построить пакет приложений? –
Использовать относительный путь вместо абсолютного пути в 'appmain.html' –
@DaveNewton благодарит за ваш ответ и извините меня за мое объяснение, но мой вопрос: _why_ У меня ошибка 404, связанная с GET источников скрипта _only_ при использовании номер порта. См. Пример EDIT. – mpogg