我正在尝试连接客户端服务器和其他api服务器。我在后端使用角度js,在后端使用loopback。
在lb-services.js上我将基本网址更改为:
var urlBase = 'http://localhost:3000/api';
我的角度js在端口4000上运行。但是当我向其余的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.
无论如何我可以代理连接或使两台服务器一起正常工作吗?
这是我的gulp / 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, []);
});
答案 0 :(得分:1)
无论如何,我可以代理连接或使两台服务器都能正常工作 在一起吗?
令人惊讶的是,您收到此错误,因为环回默认启用CORS。值得查看loopback服务器中的middleware.json文件,看看cors.params.origin是否为true。 Here是供您参考的文档链接。
我不确定您是如何更改urlBase以访问其余api的。我使用here描述的角度模块配置完成了它。
答案 1 :(得分:0)
您可以为LoopBack API添加CORS支持:
https://docs.strongloop.com/display/public/LB/Security+considerations#Securityconsiderations-CORS