【问题标题】:GET http://localhost:4000/rugs 500 (Internal Server Error)GET http://localhost:4000/rugs 500(内部服务器错误)
【发布时间】:2019-11-01 15:07:20
【问题描述】:

我正在尝试制作 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' },
];

【问题讨论】:

标签: node.js angularjs routing mean-stack crud


【解决方案1】:

确保前端文件 rug.service.ts 中的“this.http.get/put/post”与中的“rugRoutes.route(pathname).get/put/post(...)”匹配后端文件 rug.route.js。

【讨论】:

    猜你喜欢
    • 2012-02-23
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2012-03-16
    • 2021-09-07
    • 2019-02-16
    相关资源
    最近更新 更多