Меню

Gulp ошибка cannot get

First of all, I’m following Menno Pietersen’s tutorial on Rapid MODx Workflow. I’m pretty positive I’ve followed it accurately, but for some reason when I do ‘gulp watch’ in my project folder I get a blank localhost:3000 page showing «Cannot GET /».

I’m not that familiar with all of the moving parts here, so I’m not sure where to even start as to why I’m getting this error instead of seeing my site. I’ve Googled it and come up with various other isses that don’t seem related to my setup and/or tools used… and I’ve tried poking around myself and figuring it out, but I’m just spinning my wheels at this point.

Has anyone else tried this setup and encountered this? Or possibly have any idea where I should start?

I appreciate the help. I can give further information if need be. Thanks.

NOTE: If I put an index.html file in the project root then it displays that, but I’m not sure why it’s not showing the modx site or how to fix it so it does.

UPDATE: I figured out that in my gulpfile.js, the gulp.task browser-sync was setup to use ‘baseDir’.. I commented that out and used the proxy option and set it to ‘localhost’. Fixed.

После выполнения всех последовательных шагов в уроке 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 

Because it works only with index.html by default, for example:

[email protected]:~/Templates/browsersync-project$ ls 

brow.html  css

[email protected]:~/Templates/browsersync-project$ browser-sync start --server --files '.'

Expected result:

Cannot GET/

In order to see your static web-page in the web-browser instead of that annoying message you have to rename a file brow.html to index.html. This will solve Cannot GET/ problem.

P.S. Where you are installing a browser-sync doesn’t matter. Just type npm install -g browser-sync whatever directory you are in, and after double check browser-sync --version.

Using BrowserSync as a server only works if you’re running a static site, so PHP won’t work here.

Looks like you’re using XAMPP to serve your site, you can use BrowserSync to proxy your localhost.

Example:

browser-sync start --proxy localhost/yoursite

References:

  • http://www.browsersync.io/docs/command-line/#proxy-example
  • https://github.com/BrowserSync/browser-sync/issues/5

This article was extreamly helpful for getting browsersync to work with a PHP site.

These are what the configurations for both Grunt and Gulp should look like (taken from the article)

Grunt

You will need the grunt-php plugin

grunt.loadNpmTasks('grunt-browser-sync');
grunt.loadNpmTasks('grunt-php');
grunt.loadNpmTasks('grunt-contrib-watch');

grunt.initConfig({
    watch: {
        php: {
            files: ['app/**/*.php']
        }
    },
    browserSync: {
        dev: {
            bsFiles: {
                src: 'app/**/*.php'
            },
            options: {
                proxy: '127.0.0.1:8010', //our PHP server
                port: 8080, // our new port
                open: true,
                watchTask: true
            }
        }
    },
    php: {
        dev: {
            options: {
                port: 8010,
                base: 'path/to/root/folder'
            }
        }
    }
});

grunt.registerTask('default', ['php', 'browserSync', 'watch']);

Gulp

You will need the gulp-connect-php plugin

// Gulp 3.8 code... differs in 4.0
var gulp = require('gulp'),
    php = require('gulp-connect-php'),
    browserSync = require('browser-sync');

var reload  = browserSync.reload;

gulp.task('php', function() {
    php.server({ base: 'path/to/root/folder', port: 8010, keepalive: true});
});
gulp.task('browser-sync',['php'], function() {
    browserSync({
        proxy: '127.0.0.1:8010',
        port: 8080,
        open: true,
        notify: false
    });
});
gulp.task('default', ['browser-sync'], function () {
    gulp.watch(['build/*.php'], [reload]);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
let gulp = require("gulp");
let project_folder = "dist";
let source_folder = "#src";
let f = require("fs");
 
let path = {
    build:{
        html:project_folder +"/",
        css:project_folder + "/css/",
        js:project_folder + "/js/",
        img:project_folder+ "/img/",
        fonts:project_folder + "/fonts/"
    },
    src:{
        html: [ source_folder +"/*.html", "!" + source_folder + "/_*.html"],
        css:source_folder + "/scss/style.scss",
        js:source_folder + "/js/script.js",
        img:source_folder + "/img/**/*.{jpg,png,svg,gif,ico,webp}",
        fonts:source_folder + "/fonts/*.ttf"
    },
    watch:{
        html:source_folder +"/**/*.html",
        css:source_folder + "/scss/**/*.scss",
        js:source_folder + "/js/**/*.js",
        img:source_folder + "/img/**/*.{jpg,png,svg,gif,ico,webp}",
    },
    clean:"./" + project_folder + "/"
}
let {src, dest} = require ("gulp")
browsersync = require ("browser-sync").create()
del = require("del")
fileinclude = require("gulp-file-include")
scss = require("gulp-sass")
autoprefixer = require("gulp-autoprefixer")
group_media = require("gulp-group-css-media-queries")
clean_css = require("gulp-clean-css")
Rename = require("gulp-rename")
uglify = require("gulp-uglify-es").default;
imagemin = require("gulp-imagemin")
webp = require("gulp-webp")
webphtml = require("gulp-webp-html")
webpcss = require("gulp-webp-css")
svgSprite = require("gulp-svg-sprite")
ttf2woff = require("gulp-ttf2woff")
ttf2woff2 = require("gulp-ttf2woff2")
Fonter = require("gulp-fonter")
 
function browserSync() {
    browsersync.init({
        server: {
            baseDir: "./" + project_folder + "/"
        },
        port: 3000,
        notify: false
    })
}
 
function html() {
    return src(path.src.html)
        .pipe(fileinclude())
        .pipe(webphtml())
        .pipe(dest(path.build.html))
        .pipe(browsersync.stream())
}
 
function css() {
    return src(path.src.css)
        .pipe (
            scss({
                outputStyle: "expanded"
            })
        )
        .pipe(dest(path.build.css))
        .pipe (group_media())
        .pipe (
            autoprefixer ({
                overrideBrowserslist: ["last 5 versions"],
                cascade: true
            })
        )
        .pipe(webpcss())
        .pipe(dest(path.build.css))
        .pipe (clean_css())
        .pipe (
            Rename ({
                extname: ".min.css"
            })
        )
        .pipe(dest(path.build.css))
        .pipe(browsersync.stream())
}
 
function js() {
    return src(path.src.js)
        .pipe(fileinclude())
        .pipe(dest(path.build.js))
        .pipe (
            uglify()
        )
        .pipe (
            Rename ({
                extname: ".min.js"
            })
        )
        .pipe(dest(path.build.js))
        .pipe(browsersync.stream())
}
 
function images() {
    return src(path.src.img)
        .pipe (
            webp ({
             quality:70
            })
        )
        .pipe(dest(path.build.img))
        .pipe(src(path.src.img))
        .pipe(
            imagemin ({
                progressive: true,
                svgoPlugins: [{removeViewBox: false}],
                interlaced: true,
                optimizationLevel: 3
            })
        )
        .pipe(fileinclude())
        .pipe(dest(path.build.img))
        .pipe(browsersync.stream())
}
 
gulp.task('otf2ttf', function () {
    return gulp.src([source_folder + '/fonts/*.otf'])
        .pipe(Fonter({
            formats: ['ttf']
        }))
        .pipe(dest(source_folder + '/fonts/'))
})
 
 
gulp.task('svgSprite', function () {
    return gulp.src([source_folder + '/iconsprite/*.svg'])
        .pipe(svgSprite({
            mode: {
                stack: {
                    sprite: "../icons/icons.svg", // sprite file name
                     example: true
                }
            },
        }
        ))
    .pipe(dest(path.build.img))
})
 
function fonts() {
    src(path.src.fonts)
        .pipe(ttf2woff())
        .pipe(dest(path.build.fonts))
         return src(path.src.fonts)
        .pipe(ttf2woff2())
        .pipe(dest(path.build.fonts))
 
}
 
    function watchFiles() {
        gulp.watch( [path.watch.html], html )
        gulp.watch( [path.watch.css], css )
        gulp.watch( [path.watch.js], js )
        gulp.watch( [path.watch.img], images )
    }
 
    function clean() {
        return del( path.clean );
    }
 
    let build = gulp.series( clean, gulp.parallel( js, css, html, images, fonts ) );
    let watch = gulp.parallel( build, browserSync, watchFiles );
 
    exports.fonts = fonts;
    exports.images = images;
    exports.js = js;
    exports.css = css;
    exports.build = build;
    exports.html = html;
    exports.watch = watch;
    exports.default = watch;

Я хочу включить режим HTML5 для своего приложения. Я установил следующий код для конфигурации, как показано здесь:

return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {

    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix = '!';

    $routeProvider.when('/', {
        templateUrl: '/views/index.html',
        controller: 'indexCtrl'
    });
    $routeProvider.when('/about',{
        templateUrl: '/views/about.html',
        controller: 'AboutCtrl'
    });

Как вы можете видеть, я использовал $locationProvider.html5mode, и я изменил все свои ссылки в ng-ref, чтобы исключить /#/.

Проблема

На данный момент я могу перейти на localhost:9000/ и увидеть страницу индекса и перейти на другие страницы, например localhost:9000/about.

Однако проблема возникает, когда я обновляю страницу localhost:9000/about. Я получаю следующий вывод: Cannot GET /about

Если я посмотрю на сетевые вызовы:

Request URL:localhost:9000/about
Request Method:GET

Если я сначала перейду к localhost:9000/, а затем нажмите кнопку, которая переходит на /about, я получаю:

Request URL:http://localhost:9000/views/about.html

Что делает страницу безупречной.

Как включить angular для получения правильной страницы при обновлении?

Спасибо заранее.

    • 39993

    • 8 Posts
    • Send PM

    First of all, I’m following Menno Pietersen’s tutorial on Rapid MODx Workflow. I’m pretty positive I’ve followed it accurately, but for some reason when I do ‘gulp watch’ in my project folder I get a blank localhost:3000 page showing «Cannot GET /».

    I’m not that familiar with all of the moving parts here, so I’m not sure where to even start as to why I’m getting this error instead of seeing my site. I’ve Googled it and come up with various other isses that don’t seem related to my setup and/or tools used… and I’ve tried poking around myself and figuring it out, but I’m just spinning my wheels at this point.

    Has anyone else tried this setup and encountered this? Or possibly have any idea where I should start?

    I appreciate the help. I can give further information if need be. Thanks.

    NOTE: If I put an index.html file in the project root then it displays that, but I’m not sure why it’s not showing the modx site or how to fix it so it does.

    UPDATE: I figured out that it was a browser-sync issue. In my gulpfile.js, the gulp.task browser-sync was setup with ‘baseDir’.. I changed it to the proxy option and set it to ‘localhost’ and it fixed it.

    [ed. note: kevinhamil last edited this post 7 years, 9 months ago.]

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Guitar pro 7 ошибка при запуске 0xc000007b
  • Guitar pro 6 ошибка загрузки