Ошибка cannot get при запуске browser sync

I am learning the front-end build system currently gulp, i want to use brower-sync and the problem is it is not throwing an error in the commad line but instead when it brings up the browser it will not display my html file and it will say «Cannot GET /» error in the browser window. This is my gulpfile.js code

var gulp = require('gulp'),
   uglify = require('gulp-uglify'),
   compass= require('gulp-compass'),
   plumber = require('gulp-plumber'),
   autoprefixer = require('gulp-autoprefixer'),
   browserSync = require('browser-sync'),
   reload = browserSync.reload,
   rename = require('gulp-rename');


gulp.task('scripts', function() {
   gulp.src(['public/src/js/**/*.js', '!public/src/js/**/*.min.js'])
      .pipe(plumber())
      .pipe(rename({suffix: '.min'}))
      .pipe(uglify())
      .pipe(gulp.dest('public/src/js/'));
});

gulp.task('styles', function() {
   gulp.src('public/src/scss/main.scss')
      .pipe(plumber())
      .pipe(compass({
          config_file: './config.rb',
          css: './public/src/css/',
          sass: './public/src/scss/'
      }))
     .pipe(autoprefixer('last 2 versions'))
     .pipe(gulp.dest('public/src/css/'))
     .pipe(reload({stream:true}));
});


gulp.task('html', function() {
  gulp.src('public/**/*.html');
});  

gulp.task('browser-sync', function() {
    browserSync({
      server: {
         baseDir: "./public/"
      }
   });
});

gulp.task('watch', function() {
   gulp.watch('public/src/js/**/*.js', ['scripts']);
   gulp.watch('public/src/scss/**/*.scss', ['styles']);
   gulp.watch('public/**/*.html', ['html']);
});

gulp.task('default', ['scripts', 'styles', 'html', 'browser-sync', 'watch']);

i am using windows and git bash and version is "browser-sync": "^2.12.5" so what is the problem and try to explain for me in order to get something out of it.

I am learning the front-end build system currently gulp, i want to use brower-sync and the problem is it is not throwing an error in the commad line but instead when it brings up the browser it will not display my html file and it will say «Cannot GET /» error in the browser window. This is my gulpfile.js code

var gulp = require('gulp'),
   uglify = require('gulp-uglify'),
   compass= require('gulp-compass'),
   plumber = require('gulp-plumber'),
   autoprefixer = require('gulp-autoprefixer'),
   browserSync = require('browser-sync'),
   reload = browserSync.reload,
   rename = require('gulp-rename');


gulp.task('scripts', function() {
   gulp.src(['public/src/js/**/*.js', '!public/src/js/**/*.min.js'])
      .pipe(plumber())
      .pipe(rename({suffix: '.min'}))
      .pipe(uglify())
      .pipe(gulp.dest('public/src/js/'));
});

gulp.task('styles', function() {
   gulp.src('public/src/scss/main.scss')
      .pipe(plumber())
      .pipe(compass({
          config_file: './config.rb',
          css: './public/src/css/',
          sass: './public/src/scss/'
      }))
     .pipe(autoprefixer('last 2 versions'))
     .pipe(gulp.dest('public/src/css/'))
     .pipe(reload({stream:true}));
});


gulp.task('html', function() {
  gulp.src('public/**/*.html');
});  

gulp.task('browser-sync', function() {
    browserSync({
      server: {
         baseDir: "./public/"
      }
   });
});

gulp.task('watch', function() {
   gulp.watch('public/src/js/**/*.js', ['scripts']);
   gulp.watch('public/src/scss/**/*.scss', ['styles']);
   gulp.watch('public/**/*.html', ['html']);
});

gulp.task('default', ['scripts', 'styles', 'html', 'browser-sync', 'watch']);

i am using windows and git bash and version is "browser-sync": "^2.12.5" so what is the problem and try to explain for me in order to get something out of it.

После выполнения всех последовательных шагов в уроке 3.4. Планировщик задач Gulp после запуска команды gulp в терминале появляется 
gulp
[10:40:51] Using gulpfile ~DesktopУчебный 1Projekt Ubergulpfile.js
[10:40:51] Starting ‘default’…
[10:40:51] Starting ‘watch’…
[10:40:51] Starting ‘server’…
[10:40:51] Starting ‘styles’…
[10:40:51] Finished ‘styles’ after 127 ms
[Browsersync] Access URLs:
—————————————
Local: http://localhost:3000
External: http://192.168.31.219:3000
—————————————
UI: http://localhost:3001
UI External: http://localhost:3001
—————————————
[Browsersync] Serving files from: src  Далее запускается браузер в нем следующая ошибка Cannot GET в адресной строке http://localhost:3000. переустановка пакетов результата не дала та же ошибка. 

Package json 

{
  «name»: «scr»,
  «version»: «1.0.0»,
  «main»: «index.js»,
  «scripts»: {
    «test»: «echo «Error: no test specified» && exit 1″
  },
  «author»: «»,
  «license»: «ISC»,
  «devDependencies»: {
    «browser-sync»: «^2.26.7»,
    «gulp»: «^4.0.2»,
    «gulp-autoprefixer»: «^7.0.1»,
    «gulp-clean-css»: «^4.3.0»,
    «gulp-cli»: «^2.3.0»,
    «gulp-rename»: «^2.0.0»,
    «gulp-sass»: «^4.1.0»
  },
  «description»: «»
}

Файл  gulpfile.json скачан с репозитория 

const gulp        = require(‘gulp’);
const browserSync = require(‘browser-sync’);
const sass        = require(‘gulp-sass’);
const cleanCSS = require(‘gulp-clean-css’);
const autoprefixer = require(‘gulp-autoprefixer’);
const rename = require(«gulp-rename»);

gulp.task(‘server’, function() {

    browserSync({
        server: {
            baseDir: «src»
        }
    });

    gulp.watch(«src/*.html»).on(‘change’, browserSync.reload);
});

gulp.task(‘styles’, function() {
    return gulp.src(«src/sass/**/*.+(scss|sass)»)
        .pipe(sass({outputStyle: ‘compressed’}).on(‘error’, sass.logError))
        .pipe(rename({suffix: ‘.min’, prefix: »}))
        .pipe(autoprefixer())
        .pipe(cleanCSS({compatibility: ‘ie8’}))
        .pipe(gulp.dest(«src/css»))
        .pipe(browserSync.stream());
});

gulp.task(‘watch’, function() {
    gulp.watch(«src/sass/**/*.+(scss|sass)», gulp.parallel(‘styles’));
})

gulp.task(‘default’, gulp.parallel(‘watch’, ‘server’, ‘styles’));

В чем ошибка не могу понять поэтапно повторял несколько раз те же шаги результат один

при запуске команды gulp запускается браузер а там ошибка Cannot GET.

Помогите Пожайлуста кто может!

index.html лежит в папке src 

Я использую gulp. Задачи запускаются, создавая необходимые папки. Но я получаю Cannot GET / error при запуске в браузере. Я прикрепил изображение структуры моего проекта, а также вывод в командной строке выходные данные командной строки. Структура проекта.My index.html содержит следующее

<!DOCTYPE html>
<html lang="en" ng-app="helloWorldApp">
    <head>
        <title>Angular hello world app</title>
        <link href="css/main.css" rel="stylesheet">
    </head>
    <body>
        <ng-view class="view"></ng-view>
    </body>
    <script src="js/scripts.js"></script>
</html>

Я хочу знать, почему это не может быть получено или не направлено должным образом и что должно быть сделано. Таким образом, проблема в том, что когда сервер работает на локальном хосте, и я нажимаю на localhost: 3000 / в браузере, он говорит, что не может получить белый фон. Следующим является мой gulpfile.js

const gulp = require('gulp');
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();

const scripts = require('./scripts');
const styles = require('./styles');

var devMode = false;



gulp.task('css',function(){
    gulp.src(styles)
        .pipe(concat('main.css'))
        .pipe(gulp.dest('./dist/css'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('js',function(){
    gulp.src(scripts)
        .pipe(concat('scripts.js'))
        .pipe(gulp.dest('./dist/js'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('html',function(){
    gulp.src('./templates/**/*.html')
        .pipe(gulp.dest('./dist/html'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('build',function(){

    gulp.start(['css','js','html']);
     console.log("finshed build");
});

gulp.task('browser-sync',function(){
    browserSync.init(null,{
        open : false,
        server : {
            baseDir : 'dist'
        }
    });
     console.log("finshed browser ");
});

gulp.task('start',function(){
    devMode = true;
    gulp.start(['build','browser-sync']);
    gulp.watch(['./css/**/*.css'],['css']);
    gulp.watch(['./js/**/*.js'],['js']);
    gulp.watch(['./templates/**/*.html'],['html']); 
});

2 ответа

Лучший ответ

Вам нужно указать browserSync на файл dist/html/index.html в качестве начальной страницы с index.

gulp.task('browser-sync',function(){
    browserSync.init(null,{
        open : false,
        server : {
            baseDir : 'dist',
            index : "html/index.html"
        }
     });
     console.log("finshed browser ");
});


2

lofihelsinki
5 Апр 2017 в 08:53

  

Cool_Profi

14.08.18 — 12:08

Решил посмотреть на этого зверя (книжка приличная попалась)

Поставил ноду. Все пути проверил.

Добавил browser-sync

Нарисовал примитивный html (hello world)

Зашёл в каталог, где html лежит и сказал

browser-sync start —server —files «stylesheets/*.css, *.html»

Оно мне ответило

[Browsersync] Access URLs:

———————————-

       Local: http://localhost:3000

    External: http://10.0.0.25:3000

———————————-

          UI: http://localhost:3001

UI External: http://10.0.0.25:3001

———————————-

[Browsersync] Serving files from: stylesheets/*.css, *.html

и запустило хром на localhost:3000

и я вижу ответ Cannot get /

ПРричём если заглянуть в код — видно, что это отдаёт сам browser-sync

Что я не так сделал?

  

Вафель

1 — 14.08.18 — 12:10

а почему именно браузер синк выбрал?

  

Cool_Profi

2 — 14.08.18 — 12:11

(1) В книжке написано )))

Я пока в этом ни в зуб

  

Вафель

3 — 14.08.18 — 12:14

(2) а ты хочешь прям сразу веб сервер свой писать? бэкенд?

  

Вафель

5 — 14.08.18 — 12:14

для начала лучше express наверно, более популярный веб-сервер на ноде

  

Вафель

6 — 14.08.18 — 12:15

(4) вебпак — это же бандлер, а не вебсервер

  

Garykom

9 — 14.08.18 — 12:17

  

Asmody

11 — 14.08.18 — 12:21

Вообще-то, browser-sync — это хрень, которая обновляет страницу в браузере при изменении исходного кода.

При чем тут вебпаки и экспрессы?

Это, как бы, раз.

Во-вторых, в vscode есть кучка плагинов типа Live Server, которые делают тоже самое.

  

Fragster

12 — 14.08.18 — 12:21

вебпак нужен для сборки фронтенда и гибридных приложений

для серверной части мне понравился express

  

Asmody

13 — 14.08.18 — 12:22

(10) Если у тебя полторы странички с простым css, нахрена тащить монстра webpack?

  

Fragster

14 — 14.08.18 — 12:23

(13) если у тебя не фронтенд, а бэкенд :)

  

Fragster

15 — 14.08.18 — 12:23

а с фронтендом вебпак лучше

  

Asmody

17 — 14.08.18 — 12:24

(14) Какое отношение browser-sync имеет к бэку?

Ребят, вы хоть определитесь, где молоток, а где стамеска.

  

Cool_Profi

19 — 14.08.18 — 12:25

(9) Там про скриптование. У меня же пока вообще нет скриптов..

  

Garykom

22 — 14.08.18 — 12:27

Мдя как похоже на споры файловая 1С или серверная причем обязательно холивар винда vs линукс и mssql vs postgres

Новичок nodejs изучает ему даже express пока лишнее, надо основы понять, на голом node свой вручную сервер поднять.

Затем уже лезти по все эти фремворки-кофемашины «все в одном» причем webpack это как nginx поверх апача

  

Cool_Profi

23 — 14.08.18 — 12:35

Спецы закончились ? ((

  

Вафель

24 — 14.08.18 — 12:37

(23) а что тут много спецов по браузер синку???

  

Fragster

25 — 14.08.18 — 12:38

а зачем вообще браузер? для начального изучения выводи в консоль пока

  

Вафель

26 — 14.08.18 — 12:39

index.html файл то есть?

  

Вафель

27 — 14.08.18 — 12:40

  

Вафель

28 — 14.08.18 — 12:41

  

Cool_Profi

29 — 14.08.18 — 13:16

(26) Разумеется, есть

  

Garykom

30 — 14.08.18 — 13:21

(29) Покажи плиз свой index.html

  

Garykom

31 — 14.08.18 — 13:21

(30)+ там случаем вызова php нету?

  

Вафель

32 — 14.08.18 — 13:22

(31) другая ошибка была бы.
явно же не может найти файл индекс.хтмл

  

Cool_Profi

33 — 14.08.18 — 13:23

(30)

<!DOCTYPE html>

<html lang=»en» dir=»ltr»>

<head>

  <meta charset=»utf-8″>

  <title>ottergram</title>

</head>

<body>

  <header>

    <h1>ottergram</h1>

  </header>

</body>

</html>

  

Cool_Profi

34 — 14.08.18 — 13:28

  

Вафель

35 — 14.08.18 — 13:29

(34) если бы было все на месте, то работало бы

  

Cool_Profi

36 — 14.08.18 — 13:30

(35) Я тебе картинку показал. ЧТо не так в ней?

  

Вафель

37 — 14.08.18 — 13:31

картинка не работает

  

Cool_Profi

38 — 14.08.18 — 13:34

  

Asmody

39 — 14.08.18 — 13:34

Даже картинку расшарить не в силах. Чего уж там до высоких материй

  

Вафель

40 — 14.08.18 — 13:35

сейчас попробовал браусер-сеинк.
все работает
правда я запускал
browser-sync start —server

  

Вафель

41 — 14.08.18 — 13:36

и так
browser-sync start —server —files «stylesheets/*.css, *.html»
тоже работает?
Может нода не той версии?

  

Вафель

42 — 14.08.18 — 13:37

у меня 8.11.1

  

Cool_Profi

43 — 14.08.18 — 13:38

(41) нода 8.11.3 LTS

  

Cool_Profi

44 — 14.08.18 — 13:39

А вот с —files работает…

В книге ошибка? Они там на 5.* демонстрируют…

Я ж говорю — первые пробы…

  

Вафель

45 — 14.08.18 — 13:40

(44) тоже работает

В настоящее время я использую новейшую версию Browser Sync (2.24.6), установленную через npm install -g browser-sync, и я сделал это в моем C:UsersUSERNAMEGoogle Drive. Я использую Gulp.

Я запускаю синхронизацию браузера, запустив browser-sync start —server —files ‘*.html, css/*.css, js/*.js’ в bash, и мой проект открывается. Проект обновляется, как и ожидалось, когда я меняю файлы HTML, CSS и / или JS.

Однако, когда я редактирую свой файл package.json (который находится не в том же каталоге) в «сценариях» с «start»: browser-sync start —server —files ‘*.html, css/*.css, js/*.js’, а затем запускаю npm start в моей консоли bash, я получаю страницу, но все, что я вижу, это Cannot GET /, а не мой проект.

Кроме того, если я попытаюсь использовать browser-sync start —server —files ‘*.html, css/*.css, js/*.js’ или любой другой проект, я получаю ту же ошибку.

Если я сделаю gulp browser-sync, то получу:

[06:03:14] Working directory changed to ~Google Drive
[06:03:15] Using gulpfile ~Google Drivegulpfile.js
[06:03:15] Starting 'browser-sync'...
[Browsersync] Access URLs:
 --------------------------------------
       Local: http://localhost:3000
    External: http://192.168.1.116:3000
 --------------------------------------
          UI: http://localhost:3001
 UI External: http://192.168.1.116:3001
 --------------------------------------
[Browsersync] Serving files from: ./

Вот мой gulpfile.js:

const gulp = require("gulp");
const browserSync = require('browser-sync').create();

gulp.task('browser-sync', function () {
  browserSync.init({
     server: {
        baseDir: './',
     }
  });
});

А вот и мой файл package.json:

{
  "name": "eslint-test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "dependencies": {
    "browser-sync": "^2.24.6",
    "gulp-sass": "^4.0.1"
  },
  "devDependencies": {
    "eslint": "^4.18.1",
    "eslint-config-airbnb-base": "^12.1.0",
    "eslint-plugin-import": "^2.9.0",
    "gulp": "^4.0.0"
  },
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "browser-sync start --server --files '*.html, css/*.css, js/*.js'"
  },
  "author": "",
  "license": "ISC"
}

Прошу прощения, если это не подходящее место, но я искал и смотрел видео около 2 часов, но не нашел ответов. Я ценю любую помощь / ссылки.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Pick a username
Email Address
Password

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

После выполнения всех последовательных шагов в уроке 3.4. Планировщик задач Gulp после запуска команды gulp в терминале появляется 
gulp
[10:40:51] Using gulpfile ~DesktopУчебный 1Projekt Ubergulpfile.js
[10:40:51] Starting ‘default’…
[10:40:51] Starting ‘watch’…
[10:40:51] Starting ‘server’…
[10:40:51] Starting ‘styles’…
[10:40:51] Finished ‘styles’ after 127 ms
[Browsersync] Access URLs:
—————————————
Local: http://localhost:3000
External: http://192.168.31.219:3000
—————————————
UI: http://localhost:3001
UI External: http://localhost:3001
—————————————
[Browsersync] Serving files from: src  Далее запускается браузер в нем следующая ошибка Cannot GET в адресной строке http://localhost:3000. переустановка пакетов результата не дала та же ошибка. 

Package json 

{
  «name»: «scr»,
  «version»: «1.0.0»,
  «main»: «index.js»,
  «scripts»: {
    «test»: «echo «Error: no test specified» && exit 1″
  },
  «author»: «»,
  «license»: «ISC»,
  «devDependencies»: {
    «browser-sync»: «^2.26.7»,
    «gulp»: «^4.0.2»,
    «gulp-autoprefixer»: «^7.0.1»,
    «gulp-clean-css»: «^4.3.0»,
    «gulp-cli»: «^2.3.0»,
    «gulp-rename»: «^2.0.0»,
    «gulp-sass»: «^4.1.0»
  },
  «description»: «»
}

Файл  gulpfile.json скачан с репозитория 

const gulp        = require(‘gulp’);
const browserSync = require(‘browser-sync’);
const sass        = require(‘gulp-sass’);
const cleanCSS = require(‘gulp-clean-css’);
const autoprefixer = require(‘gulp-autoprefixer’);
const rename = require(«gulp-rename»);

gulp.task(‘server’, function() {

    browserSync({
        server: {
            baseDir: «src»
        }
    });

    gulp.watch(«src/*.html»).on(‘change’, browserSync.reload);
});

gulp.task(‘styles’, function() {
    return gulp.src(«src/sass/**/*.+(scss|sass)»)
        .pipe(sass({outputStyle: ‘compressed’}).on(‘error’, sass.logError))
        .pipe(rename({suffix: ‘.min’, prefix: »}))
        .pipe(autoprefixer())
        .pipe(cleanCSS({compatibility: ‘ie8’}))
        .pipe(gulp.dest(«src/css»))
        .pipe(browserSync.stream());
});

gulp.task(‘watch’, function() {
    gulp.watch(«src/sass/**/*.+(scss|sass)», gulp.parallel(‘styles’));
})

gulp.task(‘default’, gulp.parallel(‘watch’, ‘server’, ‘styles’));

В чем ошибка не могу понять поэтапно повторял несколько раз те же шаги результат один

при запуске команды gulp запускается браузер а там ошибка Cannot GET.

Помогите Пожайлуста кто может!

index.html лежит в папке src 

У меня есть gulpfile выполняющий обработку css и livereload:

const gulp         = require('gulp'),
	  browserSync  = require('browser-sync'),
	  concat       = require('gulp-concat'),
	  cleanCSS     = require('gulp-clean-css'),
	  del          = require('del'),
	  autoprefixer = require('gulp-autoprefixer');

gulp.task('styles', function() {
	return gulp.src('./css/*.css')
		.pipe(concat('style.css'))
		.pipe(autoprefixer())
		.pipe(cleanCss({
			level: 2
		}))
		.pipe(gulp.dest('./dist/css'))
});

gulp.task('clean', async function() {
	return del.sync('./dist/css/*');
});

gulp.task('browser-sync', function() {
    browserSync({
        server: { 
            baseDir: './'
        },
        notify: false
    });
});

gulp.task('watch', gulp.series('browser-sync'), function() {
    gulp.watch("./css/*.css", browserSync.reload);
    gulp.watch("./html/*.html", browserSync.reload);
});

gulp.task('default', gulp.series('watch'));
gulp.task('build', gulp.parallel('clean', 'styles'));

Билд работает хорошо, но лайв релоад упрямо отказывается работать: Если вписать папку проекта то на странице отображается «CANT GET /», а если вписать папку с html файлами то он обновляет только html и вообще не подключает стили

В чём может быть проблема?

Понравилась статья? Поделить с друзьями:
  • Ошибка cannot find utcompiledcode record for this version uninstaller
  • Ошибка cannot change visible in onshow or onhide
  • Ошибка cannot call member function without object
  • Ошибка cannot find the fakeroot binary
  • Ошибка cannot be applied to given types