我正在尝试从我的mongo数据库中的URL / carreras /:id下获取特定的carreer,该id是可以的,但是当向服务器发送的角度为null时。
我试图更改后端节点changin res.json({ 好的:是的, 卡雷拉:carrera }) 通过res.send(carrera)
carrera.service.ts
export class CarreraService {
private urlCarrera = 'http://localhost:3000/carrera';
constructor(private http: HttpClient) { }
getCarrera(id: string) {
return this.http.get(this.urlCarrera + '/' + id).pipe(
map((resp: any) => {
return resp;
})
);
}
carreras.component.ts
public id;
carreraBd: any;
constructor(public carreraServ: CarreraService,
public router: Router, public actRoute: ActivatedRoute) { }
ngOnInit() {
this.id = this.actRoute.snapshot.paramMap.get('id');
this.traerCarrera();
}
traerCarrera() {
try {
const traerCarrera = this.carreraServ.getCarrera(this.id);
console.log(this.id);
traerCarrera.subscribe(
(resp: any) => {
console.log(resp);
this.carreraBd = resp;
});
console.log(this.carreraBd);
} catch (error) {
console.log(error);
}
}
后端
carrerasController.js
exports.getCarrera = (req, res) => {
var id = req.params.id;
Carrera.findById(id, (err, carrera) => {
if (err) {
res.status(500).json({
ok: false,
err: err
});
}
if (!carrera) {
res.status(400).json({
ok: false,
err: err
});
}
res.send(carrera);
});
}
答案 0 :(得分:0)
这是核心问题。 快速修复:
在后端安装cors
npm i cors-保存
2。
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors()) // use like this.