我正在尝试制作MEAN CRUD应用。我不确定我的哪条路线已关闭,但我似乎无法与mongodb
进行通信以显示数据。当“ rug-list.component.ts”调用“ rug.service.ts”中的getRugs()
服务时,调试器似乎中断。 (我也想知道:后端文件中的路径名是否需要与前端文件中的路径名匹配?)
任何建议将不胜感激。 :)
»rug.service.ts(前端)
...
@Injectable({ providedIn: "root" })
export class RugService {
private uri = 'http://localhost:4000/rugs';
constructor(private http: HttpClient) { }
getRugs() {
return this.http.get(`${this.uri}`);
}
getRug(id: number) {
...
return this.http.get(`${this.uri}/${id}`);
}
...
deleteRug(id: number) {
return this.http.get(`${this.uri}/${id}/delete`);
}
...
}
»server.js(后端)
...
app.use('/rugs', rugRoute);
»rug.route.js(后端)
...
//list
rugRoutes.route('/').get(function (req, res) {
find(function (err, rugs) {
if (err) { console.log(err); }
else { res.json(rugs); }
});
});
//details
rugRoutes.route('/:id').get(function (req, res) {
let id = req.params.id;
findById(id, function (err, rug) {
res.json(rug);
});
});
//add
rugRoutes.route('/0/edit').post(function (req, res) {
let rug = new Rug(req.body);
rug.save().then(
() => { res.status(200).json({ 'rug': 'Rug added successfully' }); })
.catch(err => { res.status(400).send("Unable to save to database"); });
});
»app-routing.module.ts(不确定是否必要)(前端)
...
const routes: Routes = [
{ path: 'rug-list', component: RugListComponent },
{ path: 'rug-list/:id', component: RugDetailComponent },
{ path: 'rug-list/:id/edit', component: RugEditComponent },
{ path: '**', component: HomeComponent, pathMatch: 'full' },
];
最佳答案
确保前端文件rug.service.ts中的“ this.http.get / put / post”与后面文件中的“ rugRoutes.route(pathname).get / put / post(...)”相匹配,结束文件rug.route.js。