【发布时间】:2020-07-30 16:46:06
【问题描述】:
到目前为止,我正在尝试让我的角度路线在 express 中工作,它将加载页面 index.html,如果您从那里导航,它将很好地使用路线,但是如果您打开一个新浏览器并尝试直接访问到一条路线('深层链接')它将不起作用......(路线在 ng serve 中起作用)
这是我用来让它为 index.html 提供服务的东西
app.use(express.static(__dirname + '/dist'));
app.use("*",function(req,res){
res.sendFile(path.join(__dirname,"/dist/index.html"));
});
如果我尝试转到 localhost:3000 它工作正常......再次从该页面导航时,这些路线也工作正常,但如果我尝试执行 localhost:3000/room/3290sfda9328fa98(该页面包含一条路线: id) 那么它就不起作用了
这是路线的角度边
export const routes: Routes = [
{ path: '', component: StartscreenComponent },
{ path: 'room/:id', component: RoomComponent },
{ path: 'createroom', component: StartroomComponent }
];
你得到的错误是这样的:
ReferenceError: path is not defined
at /Documents/angular8/nodechat/index.js:18:18
at Layer.handle [as handle_request] (/Documents/angular8/nodechat/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:317:13)
at /Documents/angular8/nodechat/node_modules/express/lib/router/index.js:284:7
at param (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:354:14)
at param (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:365:14)
at Function.process_params (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:410:3)
at next (/Documents/angular8/nodechat/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/Documents/angular8/nodechat/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:189:13)
这里是 index.js 文件的更多内容
const express = require('express');
const app = express();
const router = express.Router();
// const proxy = require('express-http-proxy');
const helmet = require('helmet');
app.use(helmet());
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.use(express.static(__dirname + '/dist'));
app.use("*",function(req,res){
res.sendFile(path.join(__dirname,"/dist/index.html"));
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
【问题讨论】:
-
当您说
It doesn't work时,它看起来像什么?你有错误吗? -
好点@quicklikerabbit
-
我并没有真正使用 Angular,但是您是否尝试过在每条路径的前面放置 / ? React 路由器要求你这样做,即 path="/" 或 path="/room/:id"
-
@Jpark9061 添加前导斜杠会破坏角度 9 中的路线......所以不确定情况是否仍然如此。
-
您是否在索引文件的顶部
requireingpath?