使用Gulp-Connect插件在Gulp中配置中间件



我的项目的后端部分在 http://localhost:8080上运行,前端在 http://localhost:8811上的gulp-connect服务器上运行。错误消息 -

否'access-control-allow-origin'标题存在于请求的资源

是否可以在Gulp-Connect的中间软件选项中使用proxy配置删除此错误?如果是,那么我想知道如何。我尝试将响应标头"允许原素"设置为" http://localhost:8811"的响应标题,但它有效,但我想知道Gulp是否可以帮助删除该错误。

以下是我的gulpfile.js

的摘要
gulp.task('webserver',function(){
    gulpWebServer.server({
        root : ['.'],
        port : 8811,
        host : 'gulp_dev',
        livereload : true,
        middleware: function(connect, opt) {
            return [
                proxy({ changeOrigin: true,target: 'http://localhost:8080'})
            ];
        }
    });
});

service如下:

angular.module('RestAssignment').service('EmployeeService',["$resource",function($resource){
    return $resource('',{},{
        fetchEmployeeById :{
            url:'http://localhost:8080/rest/abc/getEmployeeById/2',
            method:'GET'
        },
        fetchEmployeeList : {
            url:'http://localhost:8080/rest/abc/getAllEmployees',
            method:'GET',
            isArray : true
        }
    },{});
}]);

修复:在请求的资源

安装CORS软件包:

npm install --save-dev cors

然后将其添加为中间件以进行连接:

var gulp = require('gulp');
var connect = require('gulp-connect');
var cors = require('cors');
gulp.task('connect', function() {
  connect.server({
    root: 'app',
    middleware: function() {
        return [cors()];
    }
  });
});

参考:这里

问题是我在 EmployeeService中指定了$resource中的完整URL(即使使用协议和端口(,我认为这无效,问题的第二部分是我已经有未指定proxy( path options)功能的任何路径,并且由于这些请求都得到了代理,但我只想在我获得'没有访问访问权限的情况下进行代理。启动标题'在进行REST API调用时。因此,我将Gulpfile.js更改为以下内容:

gulp.task('webserver',function(){
    gulpWebServer.server({
        root : ['.'],
        port : 8811,
        host : 'gulp_dev',
        livereload : true,
        middleware: function(connect, opt) {
            return [
                return proxy('/rest/**', { target: 'http://localhost:8080', changeOrigin : true});
            ];
        }
    });
});

EmoloyeeService to:

angular.module('LNAssignment').service('EmployeeService',["$resource",function($resource){
    return $resource('',{},{
        fetchEmployeeById :{
            url:'/rest/abc/getEmployeeById/2',
            method:'GET'
        },
        fetchEmployeeList : {
            url:'/rest/abc/getAllEmployees',
            method:'GET',
            isArray : true
        }
    },{});
}]);

现在,中间件代理完美地工作,没有任何相关的错误消息。

最新更新