我正在构建一个web应用程序,前端使用angular 7,后端使用nodejs、mongodb和expressjs。只要我与应用程序交互以导航,应用程序就会按预期运行,但当我手动键入路径时,它似乎不会命中路由的组件。它在本地运行良好,但在heroku上不起作用。
这是我的app-routing.module.ts:
const routes: Routes = [{
path: "login",
component : LoginComponent
},
{
path: "registration",
component : SignupComponent
},
{
path: "votes",
component : VotesComponent
},
{
path: "votes/:website",
component : VoteComponent
},
{
path: "**",
redirectTo: "votes"
}
];
@NgModule({
imports: [CommonModule, RouterModule.forRoot(routes, { enableTracing: false})],
exports: [RouterModule]
})
export class AppRoutingModule { }
我在Express中的所有路由都以/api/作为前缀,例如:
app.get('/api/votes', (req, res, next) => {
const limit = parseInt(req.query.limit)
db.getVotes(limit).then((votes) => {
res.json(votes);
});
(});
我这样检查JWT:
app.use(
checkJwt({ secret: process.env.JWT_SECRET }).unless({ path: [
{ url: "/api/authenticate", methods: ['POST'] },
{ url: "/api/votes", methods: ["GET"]}]})
);
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).send({ error: 'Not authorized.' });
};
});
我的投票是这样进行的:
private baseUrl = environment.apiUrl;
this.http.get<any[]>(`${this.baseUrl}/votes`, this.httpOptions))).subscribe(data => {
this.data = data;
});
baseurl在evironment.prod.ts中定义如下:
export const environment = {
production: true,
apiUrl: '/api'
};
问题来了。如果我去部署Heroku并访问
https://myurl.com
我被重定向到
https://myurl.com/votes
我可以看到请求的URL是
https://myurl.com/api/votes
,所以这一切都很好,我得到我的角度应用与所有的数据。但是如果我手动输入
https://myurl.com/votes投票
我得到JSON在浏览器中的错误“未授权”,我可以看到,所请求的URL是
https://myurl.com/votes投票
而不是
https://myurl.com/api/votes/投票
. 你知道是什么引起的吗?看起来角度不太合适。当它手动输入时,不会碰到我的任何组件。