getData() { this.regionService.getAllRegion().subscribe(data => { this.regionValue = data;
})}
getAllRegion(): Observable<RegionI> { const regionUrl = this.serverUrl + '/getRegion'; return this.httpClient.get<RegionI>(regionUrl); // return an observable
}
data type list Observable<RegionI>
export interface RegionI {
region_name: string;
created_by: string;
region_code: string;
region_id: string;
created_date: Date;
status: boolean;
}
json data calll result [{"created_date":"2023-11-27T01:59:35.280Z","_id":"6557c94afa43c40a54b3157d","region_name":"AFRICA","created_by":"TINKU","region_code":"AFR","region_id":"RE3","status":true}]
this will be shown in postman and also direct calling in web browser
same above code running perfect using json server with same result
NodeJs code as written as
api.get('/getRegion',function( req , res ){
Region.find().then((data) => {
if(!data) {
console.log(!data);
res.json("no data found");
}
else {
res.status(200).json(data);
console.log(data);
}
}); });
url call public static Live_Web_Server_Path = 'http://localhost:9003'; 'REST Api Server Node, Express, mongo Db' public static json_Web_Server_Path = 'http://localhost:3000'; "json server"
angular 16 project running fine with JSON_SERVER but when REST API is calling from Node server
then return as Observable but data will not be fetched
but direct REST API call result shown using postman or web browser [{"created_date":"2023-11-27T01:59:35.280Z","_id":"6557c94afa43c40a54b3157d","region_name":"AFRICA","created_by":"TINKU","region_code":"AFR","region_id":"RE3","status":true}]
error shows when api calling from project
Access to XMLHttpRequest at 'http://localhost:9003/master/getRegion' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. region.component.ts:50
GET http://localhost:9003/master/getRegion net::ERR_FAILED 200 (OK)
region.component.ts:50 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'http://localhost:9003/master/getRegion', ok: false, …}error:
Enable cors for the route on the server side
var cors = require('cors');
var corsOptions = {
origin: 'http://localhost:9003',
optionsSuccessStatus: 200
};
// Allow all
app.use(cors(corsOptions));
api.get('/getRegion',function( req , res ){
res.set('Access-Control-Allow-Origin', 'http://localhost:9003');
Region.find().then((data) => {
if(!data) {
console.log(!data);
res.json("no data found");
}
else {
res.status(200).json(data);
console.log(data);
}
});
});