2016-05-14 26 views
0

我試圖獲取客戶端服務器和其他api服務器來連接。我在前端和後端使用角度js。Changin迴環的基本URL lb-services.js

在LB-services.js我改變基本URL:

var urlBase = 'http://localhost:3000/api'; 

我的角度是JS在端口4000上運行,當我發表的帖子中的REST API我得到我的瀏覽器這個錯誤:

XMLHttpRequest cannot load http://localhost:3000/api/People. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access. The response had HTTP status code 404. 

無論如何,我可以代理連接或使兩個服務器正常工作嗎?

這是我一飲而盡/ server.js:

'use strict'; 

var path = require('path'); 
var gulp = require('gulp'); 
var conf = require('./conf'); 

var browserSync = require('browser-sync'); 
var browserSyncSpa = require('browser-sync-spa'); 

var util = require('util'); 

var proxyMiddleware = require('http-proxy-middleware'); 

function browserSyncInit(baseDir, browser) { 
    browser = browser === undefined ? 'default' : browser; 

    var routes = null; 
    if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) { 
    routes = { 
     '/bower_components': 'bower_components' 
    }; 
    } 

    var server = { 
    baseDir: baseDir, 
    routes: routes 
    }; 

    /* 
    * You can add a proxy to your backend by uncommenting the line below. 
    * You just have to configure a context which will we redirected and the target url. 
    * Example: $http.get('/users') requests will be automatically proxified. 
    * 
    * For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.9.0/README.md 
    */ 
    server.middleware = proxyMiddleware('/api', { 
    target: 'http://localhost:3000/api', 
    changeOrigin: true 

    }); 

    browserSync.instance = browserSync.init({ 
    startPath: '/', 
    server: server, 
    browser: browser, 
    port:4000 
    }); 
} 

browserSync.use(browserSyncSpa({ 
    selector: '[ng-app]'// Only needed for angular apps 
})); 

gulp.task('serve', ['watch'], function() { 
    browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]); 
}); 

gulp.task('serve:dist', ['build'], function() { 
    browserSyncInit(conf.paths.dist); 
}); 

gulp.task('serve:e2e', ['inject'], function() { 
    browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []); 
}); 

gulp.task('serve:e2e-dist', ['build'], function() { 
    browserSyncInit(conf.paths.dist, []); 
}); 

回答

1

反正我可以代理的連接或使兩臺服務器正常工作 ?

令人驚訝的是,由於默認情況下回送啓用了CORS,因此出現此錯誤。在你的環回服務器中檢查middleware.json文件是值得的,看看cors.params.origin是否爲真。 Here是供您參考的文檔鏈接。

我不知道你是如何改變urlBase訪問你的休息api。我已經用here所述的角度模塊配置完成了它。