Browser-sync& lite-server:http-proxy-middleware拦截不存在的url

时间:2016-11-14 04:01:58

标签: angular angular2-routing browser-sync lite-server http-proxy-middleware

我在angular2 app中有以下路由:

/** Application routes */
const routes: Routes = [
    { path: '', component: LandingComponent },
    { path: 'about', component: AboutUsComponent },    
    // catch all path, should go after all defined paths
    { path: '**', component: PageNotFoundComponent }
];

最近我不得不添加bs-config.js以下内容:

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

// note: serving from both ./dist and ./node_modules
// TODO: https?

// redirect all /api calls to the backend
var apiProxy = proxy('/api', {
    target: 'http://localhost:8080',
    pathRewrite: {
        '^/api' : '',    // rewrite path 
    },
    changeOrigin: true  // for vhosted sites
});

module.exports = {
    files : "./dist/**/*.{js, html, css}",
    server: {
        baseDir : ["./dist","node_modules"],
        middleware: {
            1: apiProxy
        },
        https : false
    },
    logLevel: "debug"
};

一切正常,除了访问404页面,即如果用户键入错误的链接我只是看到"不能GET / url"在日志中没什么有趣的。如果我只删除这三行:

        middleware: {
            1: apiProxy
        }, 

它再次开始工作,我在http://myapp/some/broken/url上获得了404页。

但是我需要代理后端相关的东西。为什么它会干扰常规的api路径,即使它只能代理api'像网址一样?

P.S。我正在使用:

"http-proxy-middleware": "^0.17.2",
"lite-server": "^2.2.2",

1 个答案:

答案 0 :(得分:0)

以某种方式通过更改为:

来修复它
    middleware: {
        1: apiProxy,
        2: require('connect-history-api-fallback')({index: '/index.html', verbose: false})
    },