本文介绍了Gulp 浏览器同步 - 通过代理重定向 API 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 gulp 和浏览器同步来重定向我的 API 请求:

I'm trying to redirect my API requests like this with gulp and browser-sync:

gulp.task('browser-sync', function () {

   var files = [
      '../index.html',
      '../views/**/*.html',
      '../assets/css/**/*.css',
      '../assets/js/**/*.js'
   ];

   var url = require('url'),
   proxy = require('proxy-middleware');
   var proxyOptions = url.parse('http://localhost:8000/api');
   proxyOptions.route = '/api';

   browserSync.init(files, {
      server: {
         baseDir: '..',
         middleware: [proxy(proxyOptions)]
      }
   });

});

但是当调用被发送到 API 时我得到这个响应:

But I get this response when a call is sent to the API:

Error: connect ECONNREFUSED
    at errnoException (net.js:904:11)
    at Object.afterConnect [as oncomplete] (net.js:895:19)

知道我做错了什么吗?

推荐答案

查看 官方文档关于使用与 Gulp 的浏览器同步.我能够在 /api 上使用代理启动并运行 BrowserSync,没有任何问题.

Checkout the official documentation about using BrowserSync with Gulp. I was able to get BrowserSync up and running with a proxy on /api with no issue.

检查以确保没有其他东西在使用端口 8000.您可以通过 port 选项更改 BrowserSync 使用的端口,当正在初始化 BrowserSync.

Check to make sure nothing else is using port 8000. You can change what port BrowserSync uses via the port option when initializing BrowserSync.

这是我最终得到的 gulpfile.js:

npm install gulp url proxy-middleware browser-sync --save-dev

// Include gulp
var gulp = require('gulp');

var url = require('url');
var proxy = require('proxy-middleware');
var browserSync = require('browser-sync');

var paths =  {
    css: ['./**/*.css', '!./node_modules/**/*']
};


// browser-sync task for starting the server.
gulp.task('browser-sync', function() {
    var proxyOptions = url.parse('http://localhost:3000/secret-api');
    proxyOptions.route = '/api';
    // requests to `/api/x/y/z` are proxied to `http://localhost:3000/secret-api/x/y/z`

    browserSync({
        open: true,
        port: 3000,
        server: {
            baseDir: "./",
            middleware: [proxy(proxyOptions)]
        }
    });
});

// Stream the style changes to the page
gulp.task('reload-css', function() {
    gulp.src(paths.css)
        .pipe(browserSync.reload({stream: true}));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch(paths.css, ['reload-css']);
});

// Default Task
gulp.task('default', ['browser-sync', 'watch']);

如果您不想单独执行 gulp 任务来重新加载/流式传输更改,您可以使用 files 选项:

If you do not want to make a separate gulp task to reload/stream the changes, you can use the files option:

browserSync({
    open: true,
    port: 3000,
    server: {
        baseDir: "./",
        middleware: [proxy(proxyOptions)]
    },
    files: paths.css
});

这篇关于Gulp 浏览器同步 - 通过代理重定向 API 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 21:05